[关闭]
@bintou 2017-12-06T21:21:10.000000Z 字数 668 阅读 1912

C语言操作文件

Source Code


C语言简单实例

请大家阅读.

  1. /* 本程序展示C语言操作文件的基本方法。
  2. The latest C standard C11 provides a new mode “x” which is exclusive create-and-open mode.
  3. Mode “x” can be used with any “w” specifier, like “wx”, “wbx”.
  4. When x is used with w, fopen() returns NULL if file already exists or could not open.
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. int main()
  9. {
  10. FILE *fp = fopen("test.txt", "wx");
  11. if (fp == NULL)
  12. {
  13. puts("Couldn't open file or file already exists");
  14. //exit(0);
  15. }
  16. else
  17. {
  18. fputs("This is a test for FILEs operation.", fp);
  19. puts("Write done.");
  20. fclose(fp);
  21. }
  22. // Open file
  23. fp = fopen("test.txt", "r");
  24. if (fp == NULL)
  25. {
  26. printf("Cannot open file. \n");
  27. exit(0);
  28. }
  29. // Read contents from file
  30. char c = fgetc(fp);
  31. while (c != EOF)
  32. {
  33. printf ("%c", c);
  34. c = fgetc(fp);
  35. }
  36. printf("\n");
  37. fclose(fp);
  38. return 0;
  39. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注