文件操作
r : 打开一个文件,文件必须存在,只允许读;
w : 新建一个文件,已存在的文件将内容清空,只允许写;
a: 打开或新建一个文件,只允许在文件末尾追写;
r+ : 打开一个文件,文件必须存在,允许读写;
w+ : 新建一个文件,已存在的文件将内容清空,允许读写;
a+: 打开或新建一个文件,可以读,但只允许在文件末尾追写;
文件操作相关的库
- istream是用于输入的流类,cin就是该类的对象。
- ostream是用于输出的流类,cout就是该类的对象。
- ifstream是用于从文件读取数据的类。
- ofstream是用于向文件写入数据的类。
- iostream是既能用于输入,又能用于输出的类。
- fstream 是既能从文件读取数据,又能向文件写入数据的类。
写入文件
#include <iostream>
int main()
{
FILE *pFile = fopen("E:\\demo.txt", "w");
if (pFile == NULL) {
printf("Fail to open file!\n");
return -1;
}
const char* mContext = "Hello World!\n";
fwrite(mContext, strlen(mContext),1,pFile);
fclose(pFile);
return 0;
}
读取文件
#include <iostream>
int main()
{
FILE *pFile = fopen("E:\\demo.txt", "a+");
if (pFile == NULL) {
printf("Fail to open file!\n");
return -1;
}
char* pBuf;//定义文件内容指针
fseek(pFile, 0, SEEK_END);//把指针移动到文件数据结尾,以获取文件长度
int size = (int)ftell(pFile);//获取文件内容长度
pBuf = new char[size + 1];//定义数组长度
rewind(pFile);//将文件指针回到文件开头
fread(pBuf, size, 1, pFile);
pBuf[size] = 0;//把读到的文件最后一位写为0,否则系统会一直寻找到0才结束
fclose(pFile);
printf(pBuf);
return 0;
}
遍历文件夹
#include <iostream>
#include <cstring>
#include <io.h>
using namespace std;
void listFiles(const char * dir);
int main()
{
char dir[200]="";
cout << "Enter a directory (ends with \'\\\'): ";
cin.getline(dir, 200);//获取用户输入
strcat_s(dir, "*.*");//在要遍历的目录后加上通配符E
listFiles(dir);
cin.get();
cin.get();
return 0;
}
void listFiles(const char * dir)
{
intptr_t handle;
_finddata_t findData;
handle = _findfirst(dir, &findData); // 查找目录中的第一个文件
if (handle == -1)
{
cout << "Failed to find first file!\n";
return;
}
do
{
if (findData.attrib & _A_SUBDIR
&& strcmp(findData.name, ".") == 0
&& strcmp(findData.name, "..") == 0
) // 是否是子目录并且不为"."或".."
cout << findData.name << "\t<dir>\n";
else
cout << findData.name << "\t" << findData.size << endl;
} while (_findnext(handle, &findData) == 0);//查找目录中的下一个文件
cout << "Done!\n";
_findclose(handle);//关闭搜索句柄
}
常见问题:
Expression:stream!=nullptr
如果fopen返回null,那么就不能对文件进行操作了,包括fclose,因为文件根本没有被打开
由通用字符名称“\u202A”表示的字符不能在当前代码页(936)中表示出来
一般是fopen中的文件路径是复制过来的导致的,可手敲一下解决这个问题。
参考:https://blog.csdn.net/gxmirror_lee/article/details/63264640