zoukankan      html  css  js  c++  java
  • fread (File input/output) – C 中文开发手册

    [
  •   C 语言中文开发手册

    fread (File input/output) - C 中文开发手册

    在头文件<stdio.h>中定义
    size_t fread(void * buffer,size_t size,size_t count,FILE * stream); (直到C99)
    size_t fread(void * restrict buffer,size_t size,size_t count,FILE * restrict stream); (自C99以来)

    从给定的输入流中读取count对象到数组中buffer,stream就像调用fgetc size每个对象的时间一样,并将结果按获得的顺序存储到连续的位置buffer,并重新解释为数组unsigned char。流的文件位置指示符按读取的字符数进行提前。如果发生错误,则流的文件位置指示符的结果值不确定。如果读取了部分元素,则其值是不确定的。

    参数

    缓冲 - 指向存储读取对象的数组的指针
    尺寸 - 每个对象的大小以字节为单位
    计数 - 要读取的对象的数量
    - 要读取的流

    返回值

    成功读取的对象数量,可能少于count发生错误或文件结束条件时的数量。如果size或者count为零,则fread返回零且不执行其他操作。fread不区分文件结束和错误,呼叫者必须使用feof并ferror确定发生的事件。

    #include <stdio.h>
     
    enum { SIZE = 5 };
    int main(void)
    {
        double a[SIZE] = {1.,2.,3.,4.,5.};
        FILE *fp = fopen("test.bin", "wb"); // must use binary mode
        fwrite(a, sizeof *a, SIZE, fp); // writes an array of doubles
        fclose(fp);
     
        double b[SIZE];
        fp = fopen("test.bin","rb");
        size_t ret_code = fread(b, sizeof *b, SIZE, fp); // reads an array of doubles
        if(ret_code == SIZE) {
            puts("Array read successfully, contents: ");
            for(int n = 0; n < SIZE; ++n) printf("%f ", b[n]);
            putchar('
    ');
        } else { // error handling
           if (feof(fp))
              printf("Error reading test.bin: unexpected end of file
    ");
           else if (ferror(fp)) {
               perror("Error reading test.bin");
           }
        }
     
        fclose(fp);
    }

    输出:

    Array read successfully, contents: 
    1.000000 2.000000 3.000000 4.000000 5.000000

    参考

    C11标准(ISO / IEC 9899:2011): 7.21.8.1 fread函数(p:335) C99标准(ISO / IEC 9899:1999): 7.19.8.1 fread函数(p:301) C89 / C90标准(ISO / IEC 9899:1990): 4.9.8.1 fread函数

  •   C 语言中文开发手册
    ]
    转载请保留页面地址:https://www.breakyizhan.com/c-3/27389.html
  • 相关阅读:
    随堂练习 磁盘管理文件系统
    随堂练习 shell脚本(二)
    随堂练习 软件包管理
    随堂练习 压缩和解压缩
    随堂练习 文本处理小工具
    随堂练习 用户和组的权限管理
    随堂练习 bash shell特性和I/O重定向及管道
    随堂练习 Linux 文件管理
    随堂练习 linux 基础知识
    C连载13-复数类型以及基本数据类型总结
  • 原文地址:https://www.cnblogs.com/breakyizhan/p/13286357.html
Copyright © 2011-2022 走看看