当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C语言 fread()用法及代码示例


C 中的 fread() 函数

原型:

    size_t fread(void *buffer, size_t length, size_t count, FILE *filename);

参数:

    void *buffer, size_t length, size_t count, FILE *filename

返回类型:size_t

函数的使用:

函数 fread() 的原型为:

    size_t fread(void *buffer, size_t length, size_t count, FILE *filename);

在文件处理中,通过fread()函数,我们读取count大小对象的数量length从输入流filename到名为的数组buffer.它返回从文件中读取的对象数。如果读取的对象较少,或者EOF在此之前遇到它会报错。

C 中的 fread() 示例

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

int main()
{
    FILE* f;
    //initialize the arr1 with values
    int arr1[5] = { 1, 2, 3, 4, 5 };
    int arr2[5];
    int i = 0;

    //open the file for write operation
    if ((f = fopen("includehelp.txt", "w")) == NULL) {
        //if the file does not exist print the string
        printf("Cannot open the file...");
        exit(1);
    }
    //write the values on the file
    if ((fwrite(arr1, sizeof(int), 5, f)) != 5) {
        printf("File write error....\n");
    }
    //close the file
    fclose(f);

    //open the file for read operation
    if ((f = fopen("includehelp.txt", "r")) == NULL) {
        //if the file does not exist print the string
        printf("Cannot open the file...");
        exit(1);
    }
    //read the values from the file and store it into the array
    if ((fread(arr2, sizeof(int), 5, f)) != 5) {
        printf("File write error....\n");
    }
    fclose(f);

    printf("The array content is-\n");
    for (i = 0; i < 5; i++) {
        printf("%d\n", arr2[i]);
    }

    return 0;
}

输出

fread example in c




相关用法


注:本文由纯净天空筛选整理自Souvik Saha大神的英文原创作品 fread() function in C language with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。