一、标准C++文件操作
ifstream 读入流
ofstream 写出流
fstream 读写流
使用步骤
1、绑定流
两种方法:
(1)ifstream infile(string filename);
ifstream infile(string filename, mode);
(2)ifstream infile; infile.open(string filename);
ifstream infile; infile.open(string filename, mode);
2、检查文件是否打开
if(infile){}
3、使用文件流
同样使用>>、<<操作符。
如:infile>>s; //读入到s中
4、关闭文件流
close()方法。
5、重新绑定文件流
需要先关闭流,再重新绑定。
6、c++目录操作
包含的头文件 #include <direct.h>
函数 mkdir(name); mkdir(name);
二、VC中文件操作
MFC中文件操作使用的类:
CFileFind 文件查找类
CFile 文件类
1、文件查找
示例代码:
CString strFileTitle;
CFileFind finder;
BOOL bWorking = finder.FindFile( "C:\\windows\\sysbkup\\*.cab ");
while(bWorking)
{
bWorking=finder.FindNextFile();
strFileTitle=finder.GetFileTitle();
}
2、文件操作
//对文件进行读操作
char sRead[2];
CFile mFile(_T( "user.txt "),CFile::modeRead);
if(mFile.GetLength() <2)
return;
mFile.Read(sRead,2);
mFile.Close();
//对文件进行写操作
CFile mFile(_T( "user.txt"), CFile::modeWrite|CFile::modeCreate);
mFile.Write(sRead,2);
mFile.Flush();
mFile.Close();
3、其他操作
CopyFile()、CreateDirectory()、DeleteFile()、MoveFile()