读写文件操作
c++方法
参考博客:基本函数介绍
直接上代码,如下
void OperationFile_Cplus() {
ofstream file;
file.open("D:/test01.txt");
int nRet = file.is_open();
if (!nRet) {
cout << "打开文件失败" << endl;
}
long pos1 = file.tellp();
char ByteToWrite[40] = "\x0a\x0a\x0a\x0a";
char ByteToRead[40] = { 0 };
file.write(ByteToWrite,strlen(ByteToWrite));//执行完该函数确实不会立刻写入文件
file.seekp(0,ios::end);
long pos2 = file.tellp();
cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
file.close();
ifstream file2;
file2.open("D://test01.txt");
nRet = file2.is_open();
if (!nRet) {
cout << "打开文件失败" << endl;
}
pos1 = 0;
file2.seekg(0, ios::end);
pos2 = file2.tellg();
cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
file2.seekg(0, ios::beg);
file2.read(ByteToRead, pos2 - pos1);
int num = file2.gcount();
cout << "实际读到的字节数:" << num <<endl;
file2.close();
cout << "================================" << endl;
file.open("D:/test02.txt",ios::binary);
nRet = file.is_open();
if (!nRet) {
cout << "打开文件失败" << endl;
}
pos1 = file.tellp();
memset(ByteToRead, 0, sizeof(ByteToRead));
file.write(ByteToWrite, strlen(ByteToWrite));//执行完该函数确实不会立刻写入文件
file.seekp(0, ios::end);
pos2 = file.tellp();
cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
file.close();
file2.open("D://test02.txt",ios::binary);
nRet = file2.is_open();
if (!nRet) {
cout << "打开文件失败" << endl;
}
pos1 = 0;
file2.seekg(0, ios::end);
pos2 = file2.tellg();
cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
file2.seekg(0, ios::beg);
file2.read(ByteToRead, pos2 - pos1);
num = file2.gcount();
cout << "实际读到的字节数:" << num << endl;
file2.close();
}
这里使用的是ofstream和ifstream,当然也可以使用fstream,但是需要注意一下两点:
1.fstream的对象以ios::in|ios::out方式去打开文件时,若文件不存在会打开失败;
2.参考博客【基本函数介绍】中提到可同步的问题,写文件时先写入流缓存,直到触发【同步】过程,在调试过程中针对此问题进行了验证如下图所示,确实存在。【ps:使用c方法也是类似的,调用fwrite函数也不是立即写入文件】
函数的执行结果和c语言方法相同,如下图所示: