fwrite() và fread() dùng để ghi/đọc file trong C.
Cú pháp fwrite()
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
Trong đó:
ptr - Con trỏ mảng phần tử sẽ ghi
size - Kích thước byte mỗi phần tử
nmemb - Số phần tử, mỗi phần tử size byte
stream - Con trỏ FILE chỉ luồng đầu ra
Cú pháp fread()
fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
Trong đó:
ptr - Con trỏ khối bộ nhớ tối thiểu size*nmemb byte
size - Kích thước byte mỗi phần tử đọc
nmemb - Số phần tử, mỗi phần tử size byte
stream - Con trỏ FILE chỉ luồng đầu vào
Thuật toán
Bắt đầu
Tạo cấu trúc Student khai báo biến
Mở file để ghi
Kiểm tra lỗi mở file
Khởi tạo biến với dữ liệu
Nếu mở thành công, ghi struct dùng fwrite
Đóng file ghi
Mở file để đọc
Kiểm tra lỗi mở file
Nếu mở thành công, đọc file dùng fread
Đóng file đọc
Kiểm tra lỗi
In dữ liệu
Kết thúcVí dụ đọc/ghi struct trong C:
Ví dụ mã
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
int roll_no;
char name[20];
};
int main() {
FILE *of;
of = fopen("c1.txt", "w");
if (of == NULL) {
fprintf(stderr, "\nError to open the file\n");
exit(1);
}
struct Student inp1 = {1, "Ram"};
struct Student inp2 = {2, "Shyam"};
fwrite(&inp1, sizeof(struct Student), 1, of);
fwrite(&inp2, sizeof(struct Student), 1, of);
if(fwrite != 0)
printf("Contents to file written successfully!\n");
else
printf("Error writing file!\n");
fclose(of);
FILE *inf;
struct Student inp;
inf = fopen("c1.txt", "r");
if (inf == NULL) {
fprintf(stderr, "\nError to open the file\n");
exit(1);
}
while(fread(&inp, sizeof(struct Student), 1, inf))
printf("roll_no = %d name = %s\n", inp.roll_no, inp.name);
fclose(inf);
}Kết quả
Contents to file written successfully! roll_no = 1 name = Ram roll_no = 2 name = Shyam