What is the usage of the fread function in the C progra…

The fread function in the C programming language is used to read files and its prototype is:

Read from the stream specified by stream and store the data in the memory location pointed to by ptr, reading count elements each of size bytes.

The function’s purpose is to read data from the specified file stream `stream` and store it in the memory space pointed to by `ptr`. The specific meanings of the parameters are as follows:

  1. ptr: a pointer pointing to the memory space where the data is stored.
  2. size: number of bytes per data item to be read.
  3. Count: Number of data items to be read.
  4. stream: specifies the file stream to be read.

The function returns the actual number of items read, which should be equal to the count parameter if the read is successful, otherwise indicating failure to read or reaching the end of the file.

Example usage:

#include <stdio.h>

int main() {
    FILE *file;
    char buffer[100];
    
    file = fopen("test.txt", "rb");
    if (file == NULL) {
        printf("打开文件失败");
        return 1;
    }
    
    size_t result = fread(buffer, sizeof(char), 10, file);
    if (result != 10) {
        printf("读取文件失败");
        return 1;
    }
    
    printf("读取的内容为:%s\n", buffer);
    
    fclose(file);
    
    return 0;
}

In the above example, firstly open a file named test.txt in binary mode “rb”, then use the fread function to read 10 bytes of content from the file and store it in the buffer array. Finally, print out the content that was read. If there is a failure in opening or reading the file, the corresponding error message will be displayed. Lastly, close the file.

bannerAds