• C++ Reference: Standard C++ Library reference: C Library: cstdio: fread


    C++官网参考链接:https://cplusplus.com/reference/cstdio/fread/

    函数
    <cstdio>
    fread
    size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
    从流中读取数据块
    stream中读取count个元素的数组,每个元素的大小为size个字节,并将它们存储在ptr指定的内存块中。
    stream的位置指示符按读取的字节总数向前移动。
    如果成功,则读取的字节总数为size*count。

    形参
    ptr
    指向内存块的指针,其大小至少为size*count个字节,转换为void*。
    size 
    要读取的每个元素的字节大小。
    size_t是无符号整型。
    count
    元素数量,每个元素的大小为size个字节。
    size_t是无符号整型。
    stream
    指向指定输入流的FILE对象的指针。

    返回值
    返回成功读取的元素总数。
    如果该数字与count形参不同,则要么发生了读取错误,要么在读取时已到达文件结束。在这两种情况下,都设置了适当的指示符,可以分别用ferrorfeof进行检查。
    如果sizecount为0,则函数返回0,并且stream状态和ptr所指向的内容保持不变。
    size_t是无符号整型。

    用例
    /* fread example: read an entire file */
    #include
    #include

    int main () {
      FILE * pFile;
      long lSize;
      char * buffer;
      size_t result;

      pFile = fopen ( "myfile.bin" , "rb" );
      if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

      // obtain file size:
      fseek (pFile , 0 , SEEK_END);
      lSize = ftell (pFile);
      rewind (pFile);

      // allocate memory to contain the whole file:
      buffer = (char*) malloc (sizeof(char)*lSize);
      if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

      // copy the file into the buffer:
      result = fread (buffer,1,lSize,pFile);
      if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

      /* the whole file is now loaded in the memory buffer. */

      // terminate
      fclose (pFile);
      free (buffer);
      return 0;

    这段代码将myfile.bin加载到动态分配的内存缓冲区中,该缓冲区可用于将文件的内容作为数组操作。

  • 相关阅读:
    23. 合并 K 个升序链表
    sql的select查询语句大全(单表查询、多表连接查询)
    Stream流、 方法引用
    【JAVA JDBC】
    pyautogui实践——10行代码实现《破事精英》里面的“凝固的桌面“
    使用 JavaScript 切换全屏模式
    红米电脑硬盘剪切
    2022年PMP考试应该注意些什么?
    【PHPWrod】使用PHPWord导出word文档
    包装类知识点
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/127340193