Thao tác với file trong C
Mở file
FILE *f = fopen("data.txt", "r"); // doc
FILE *f = fopen("data.txt", "w"); // ghi
FILE *f = fopen("data.txt", "a"); // them
Đọc file
char buffer[255];
while (fgets(buffer, 255, f) != NULL) {
printf("%s", buffer);
}
Ghi file
fprintf(f, "Hello, file!\n");
fputc('A', f);
fputs("Chuoi", f);
Đọc/ghi nhị phân
fread(&data, sizeof(data), 1, f);
fwrite(&data, sizeof(data), 1, f);
Đóng file
fclose(f);
Ví dụ
FILE *f = fopen("hello.txt", "w");
fprintf(f, "Xin chao the gioi!");
fclose(f);