fwrite()与fread()

作者:追风剑情 发布于:2020-4-2 17:07 分类:C

文件读写

示例

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define DATA_SIZE 5
  7.  
  8. int main(int argc, char* argv[])
  9. {
  10. FILE *fp;
  11. size_t size;
  12.  
  13. /* 写文件 */
  14. if ((fp = fopen("wordy", "wb+")) == NULL)
  15. {
  16. fprintf(stdout, "Can't open \"wordy\" file.\n");
  17. exit(EXIT_FAILURE);
  18. }
  19.  
  20. int num = 889;
  21. size = fwrite(&num, sizeof(int), 1, fp);
  22. printf("fwrite() return: %d\n", size);
  23.  
  24. unsigned int *dataPtr = NULL;
  25. dataPtr = (unsigned int *)malloc(sizeof(int) * DATA_SIZE);
  26. for (unsigned int i = 0; i < DATA_SIZE; i++)
  27. dataPtr[i] = i; //初始化
  28.  
  29. size = fwrite(dataPtr, sizeof(int), DATA_SIZE, fp);
  30. printf("fwrite() return: %d\n", size);
  31.  
  32. puts("Write Done!");
  33.  
  34. /* 读文件 */
  35. rewind(fp); //回到文件首地址
  36.  
  37. size = fread(&num, sizeof(int), 1, fp);
  38. printf("fread() return: %d\n", size);
  39.  
  40. size = fread(dataPtr, sizeof(int), DATA_SIZE, fp);
  41. printf("fread() return: %d\n", size);
  42.  
  43. puts("Read Done!");
  44.  
  45. if (fclose(fp) != 0)
  46. fprintf(stderr, "Error closing file\n");
  47. free(dataPtr);
  48.  
  49. system("pause");
  50. return 0;
  51. }

运行测试

11111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号