文件操作

r : 打开一个文件,文件必须存在,只允许读;
w : 新建一个文件,已存在的文件将内容清空,只允许写;
a: 打开或新建一个文件,只允许在文件末尾追写;
r+ : 打开一个文件,文件必须存在,允许读写;
w+ : 新建一个文件,已存在的文件将内容清空,允许读写;
a+: 打开或新建一个文件,可以读,但只允许在文件末尾追写;

注意:没有 rw

文件操作相关的库

  • istream是用于输入的流类,cin就是该类的对象。
  • ostream是用于输出的流类,cout就是该类的对象。
  • ifstream是用于从文件读取数据的类。
  • ofstream是用于向文件写入数据的类。
  • iostream是既能用于输入,又能用于输出的类。
  • fstream 是既能从文件读取数据,又能向文件写入数据的类。

写入文件

  1. #include <iostream>
  2. int main()
  3. {
  4. FILE *pFile = fopen("E:\\demo.txt", "w");
  5. if (pFile == NULL) {
  6. printf("Fail to open file!\n");
  7. return -1;
  8. }
  9. const char* mContext = "Hello World!\n";
  10. fwrite(mContext, strlen(mContext),1,pFile);
  11. fclose(pFile);
  12. return 0;
  13. }

读取文件

  1. #include <iostream>
  2. int main()
  3. {
  4. FILE *pFile = fopen("E:\\demo.txt", "a+");
  5. if (pFile == NULL) {
  6. printf("Fail to open file!\n");
  7. return -1;
  8. }
  9. char* pBuf;//定义文件内容指针
  10. fseek(pFile, 0, SEEK_END);//把指针移动到文件数据结尾,以获取文件长度
  11. int size = (int)ftell(pFile);//获取文件内容长度
  12. pBuf = new char[size + 1];//定义数组长度
  13. rewind(pFile);//将文件指针回到文件开头
  14. fread(pBuf, size, 1, pFile);
  15. pBuf[size] = 0;//把读到的文件最后一位写为0,否则系统会一直寻找到0才结束
  16. fclose(pFile);
  17. printf(pBuf);
  18. return 0;
  19. }

遍历文件夹

  1. #include <iostream>
  2. #include <cstring>
  3. #include <io.h>
  4. using namespace std;
  5. void listFiles(const char * dir);
  6. int main()
  7. {
  8. char dir[200]="";
  9. cout << "Enter a directory (ends with \'\\\'): ";
  10. cin.getline(dir, 200);//获取用户输入
  11. strcat_s(dir, "*.*");//在要遍历的目录后加上通配符E
  12. listFiles(dir);
  13. cin.get();
  14. cin.get();
  15. return 0;
  16. }
  17. void listFiles(const char * dir)
  18. {
  19. intptr_t handle;
  20. _finddata_t findData;
  21. handle = _findfirst(dir, &findData); // 查找目录中的第一个文件
  22. if (handle == -1)
  23. {
  24. cout << "Failed to find first file!\n";
  25. return;
  26. }
  27. do
  28. {
  29. if (findData.attrib & _A_SUBDIR
  30. && strcmp(findData.name, ".") == 0
  31. && strcmp(findData.name, "..") == 0
  32. ) // 是否是子目录并且不为"."或".."
  33. cout << findData.name << "\t<dir>\n";
  34. else
  35. cout << findData.name << "\t" << findData.size << endl;
  36. } while (_findnext(handle, &findData) == 0);//查找目录中的下一个文件
  37. cout << "Done!\n";
  38. _findclose(handle);//关闭搜索句柄
  39. }

常见问题:

Expression:stream!=nullptr

如果fopen返回null,那么就不能对文件进行操作了,包括fclose,因为文件根本没有被打开

由通用字符名称“\u202A”表示的字符不能在当前代码页(936)中表示出来

一般是fopen中的文件路径是复制过来的导致的,可手敲一下解决这个问题。
参考:https://blog.csdn.net/gxmirror_lee/article/details/63264640