C语言 fopen和fread函数解析 (2)

fread() function is the complementary of fwrite() function. fread() function is commonly used to read binary data. It accepts the same arguments as fwrite() function does.

Syntax: size_t fread(void *ptr, size_t size, size_t n, FILE *fp);

The ptr is the starting address of the memory block where data will be stored after reading from the file. The function reads n items from the file where each item occupies the number of bytes specified in the second argument. On success, it reads n items from the file and returns n. On error or end of the file, it returns a number less than n.

举两个简单的例子:

//Example 1: Reading an array from the file int arr[10]; fread(arr, sizeof(arr), 1, fp); //Example 2: Reading the structure variable struct student { char name[10]; int roll; float marks; }; struct student student_1; fread(&student_1, sizeof(student_1), 1, fp);

关于fread最值得注意的一点,fread读取文件时,会自动保留当前的读取位置,也就是说,不用自己去管读取的位置在哪个字节,读取了对应文件的部分后,会自动继续往下读取,关于这里点,可以参考https://stackoverflow.com/questions/10696845/does-fread-move-the-file-pointer,具体举个例子。

#include<stdio.h> #include<stdlib.h> struct employee { char name[50]; char designation[50]; int age; float salary } emp; int main() { FILE *fp; fp = fopen("employee.txt", "rb"); if(fp == NULL) { printf("Error opening file\n"); exit(1); } printf("Testing fread() function: \n\n"); //循环读取,会自动往后读,而不会反复读取文件的最前面的部分 while( fread(&emp, sizeof(emp), 1, fp) == 1 ) { printf("Name: %s \n", emp.name); printf("Designation: %s \n", emp.designation); printf("Age: %d \n", emp.age); printf("Salary: %.2f \n\n", emp.salary); } fclose(fp); return 0; }

输出结果:

Testing fread() function: Name: Bob Designation: Manager Age: 29 Salary: 34000.00 Name: Jake Designation: Developer Age: 34 Salary: 56000.00

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzsgpz.html