分享

fread()和fwrite()函数读写文件操作

 问见 2016-03-06



  1. #include <stdio.h>   
  2. int main()  
  3. {  
  4.     FILE* pFile;  
  5.     float buffer[] = { 2.0 , 3.0 , 8.0 };  
  6.     pFile = fopen("myfile.bin" , "wb"); // 打开文件写操作   
  7.     fwrite(buffer , 1 , sizeof(buffer) , pFile); // 把浮点数组写到文件 myfile.bin   
  8.     fclose(pFile); // 关闭文件   
  9.   
  10.     float read[3];  
  11.     pFile = fopen("myfile.bin" , "rb"); // 重新打开文件读操作   
  12.     fread(read , 1 , sizeof(read) , pFile); // 从文件中读数据   
  13.     printf("%f\t%f\t%f\n", read[0], read[1], read[2]);  
  14.   
  15.     fclose(pFile); // 关闭文件   
  16.     return 0;  
  17. }  
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     FILE* pFile;  
  5.     float buffer[] = { 2.0 , 3.0 , 8.0 };  
  6.     pFile = fopen("myfile.bin" , "wb"); // 打开文件写操作  
  7.     fwrite(buffer , 1 , sizeof(buffer) , pFile); // 把浮点数组写到文件 myfile.bin  
  8.     fclose(pFile); // 关闭文件  
  9.   
  10.     float read[3];  
  11.     pFile = fopen("myfile.bin" , "rb"); // 重新打开文件读操作  
  12.     fread(read , 1 , sizeof(read) , pFile); // 从文件中读数据  
  13.     printf("%f\t%f\t%f\n", read[0], read[1], read[2]);  
  14.   
  15.     fclose(pFile); // 关闭文件  
  16.     return 0;  
  17. }  



  1. /* fread example: read a complete file 读取一个完整的文件 */  
  2. #include <stdio.h>   
  3. #include <stdlib.h>   
  4.   
  5. int main()  
  6. {  
  7.     FILE* pFile;   //文件指针   
  8.     long lSize;   // 用于文件长度   
  9.     char* buffer; // 文件缓冲区指针   
  10.     size_t result;  // 返回值是读取的内容数量   
  11.   
  12.     pFile = fopen("myfile.bin" , "rb");  
  13.     if (pFile == NULL) {fputs("File error", stderr); exit(1);}    // 如果文件错误,退出1   
  14.   
  15.     // obtain file size:  获得文件大小   
  16.     fseek(pFile , 0 , SEEK_END); // 指针移到文件末位   
  17.     lSize = ftell(pFile);  // 获得文件长度   
  18.     rewind(pFile);  // 函数rewind()把文件指针移到由stream(流)指定的开始处, 同时清除和流相关的错误和EOF标记   
  19.   
  20.     // allocate memory to contain the whole file: 为整个文件分配内存缓冲区   
  21.     buffer = (char*) malloc(sizeof(char) * lSize); // 分配缓冲区,按前面的 lSize   
  22.     if (buffer == NULL) {fputs("Memory error", stderr); exit(2);}  // 内存分配错误,退出2   
  23.   
  24.     // copy the file into the buffer:  该文件复制到缓冲区   
  25.     result = fread(buffer, 1, lSize, pFile); // 返回值是读取的内容数量   
  26.     if (result != lSize) {fputs("Reading error", stderr); exit(3);} // 返回值如果不和文件大小,读错误   
  27.   
  28.     /* the whole file is now loaded in the memory buffer. */ //现在整个文件载入内存缓冲区   
  29.   
  30.     // 读到内存,看自己怎么使用了...............   
  31.     // ...........   
  32.   
  33.   
  34.     // terminate // 文件终止   
  35.     fclose(pFile);  
  36.     free(buffer);  
  37.     return 0;  
  38. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多