fwrite and fread are I/O functions that operate in units of records. The fread and fwrite functions are generally used for input and output of binary files.

#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

Return value: the number of records read or written. On success, the number of records returned equals nmemb. On error or when reaching the end of the file, the number of records returned is less than nmemb, and it may also return 0.

fread and fwrite are used to read and write records. A record here refers to a fixed-length sequence of bytes, such as an int, a struct, or a fixed-length array. The parameter size specifies the length of one record, while nmemb specifies how many records to read or write. These records are stored contiguously in the memory space pointed to by ptr, occupying a total of size * nmemb bytes. fread reads size * nmemb bytes from the file stream and saves them into ptr, while fwrite writes the size * nmemb bytes in ptr to the file stream.

nmemb is the number of records requested for reading or writing. The number of records returned by fread and fwrite may be less than the number of records specified by nmemb. For example, if the current read/write position is only one record's length from the end of the file, and nmemb is specified as 2 when calling fread, the return value will be 1. If the current read/write position is already at the end of the file, or an error occurs while reading the file, fread returns 0. If an error occurs while writing the file, the return value of fwrite is less than the value specified by nmemb. The following example consists of two programs: one program saves a struct to a file, and the other program reads the struct from the file.

#include <stdio.h>  
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);  
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);  

fwrite and fread reference code:

writerec.c file code

/* -------------------writerec.c--------------- */

#include <stdio.h>
#include <stdlib.h>

struct record {
    char name[10]; 
    int age;
};  

int main(void)
{  
    struct record array[2] = {{"Ken", 24}, {"Knuth", 28}}; 
    FILE *fp = fopen("d:/test.txt", "w");
    if (fp == NULL) {  
        perror("Open file recfile"); 
        exit(1);  
    }  
    fwrite(array, sizeof(struct record), 2, fp);
    fclose(fp);
    return 0;
}

readrec.c file code:

/* -------------------readrec.c----------------- */

#include <stdio.h>
#include <stdlib.h>

struct record {
    char name[10];
    int age;
};  

int main(void)  
{  
    struct record array[2]; 
    FILE *fp = fopen("d:/test.txt", "r"); 
    if (fp == NULL) {  
        perror("Open file recfile");
        exit(1);  
    }  
    fread(array, sizeof(struct record), 2, fp);  
    printf("Name1: %s\tAge1: %d\n", array[0].name, array[0].age);  
    printf("Name2: %s\tAge2: %d\n", array[1].name, array[1].age);  
    fclose(fp);  
    return 0;  
}
$ gcc writerec.c -o writerec
$ gcc readrec.c -o readrec

It was found that the generated file recfile cannot be opened directly.

Reason:We treat astruct record struct as one record. Because the struct contains padding bytes, each record occupies 16 bytes, and writing two records to the file occupies a total of 32 bytes. The recfile file generated by this program is a binary file rather than a text file, because it not only stores character data but also stores the integer data 24 and 28 (displayed in octal as 030 and 034 in the output of the od command).

Note that programs that directly read and write structs in files are not portable. If you compile and run the writebin.c program on one platform, copy the generated recfile file to another platform, and compile and run the readbin.c program on that platform, you cannot guarantee that the file contents will be read correctly, because different platforms may have different endianness (and therefore store integer data differently), and the padding of structs may also differ (so the number of bytes occupied by the same struct may differ, and the position of the age member after the name member may also differ). By using the readrec program to read the contents of the file recfile, it demonstrates that the writerec program indeed successfully wrote the records to recfile.

The contents read from recfile are as follows:

Name1: Ken    Age1: 24
Name2: Knuth  Age2: 28

Examples of fwrite and fread applications:

1. Write a string to a file:

char *str="hello,I am a test program!";  
fwrite(str,sizeof(char),strlen(str),fp)  

2. Write a character array to a file:

char str[]={'a','b','c','d','e'};  
fwrite(str,sizeof(char),sizeof(str),fp)  

3. Write an integer array to a file:

int a[]={12,33,23,24,12};

First calculate the number of array elements nmemb, then

fwrite(a,sizeof(int),nmemb,fp)

Note: Since the file generated by the program is a binary file rather than a text file, integers are represented differently on different machines, so the generated file cannot be opened directly. You can use the fread function to verify whether the data has been written to the file.

Original URL: http://purpleroom.blog.sohu.com/133812394.html