在 C 中,我们通过 FILE 结构体生成的指向 FILE 结构体的指针来操作文件。其提供了诸如 fgetc、fgets、feof等等函数,在 C++ 中重新封装了操作文件的方法,其实现在 iostream 派生的 fstream 中,实际内部实现基本原理与 C 相同。下面就分别介绍下操作文本文件和二进制文件的方法。

【操作文本文件】

#include
#include
 
using namespace std;
 
bool txt_write()
{
ofstream ofs(“abc.txt”, ios::out ios::trunc);
if (!ofs) return false;
 
ofs << “aaaaaaaaaaaaa” << endl;
ofs << “bbbbbbbbbbbbb” << endl;
ofs << “ccccccccccccc” << endl;
 
ofs.close();
return true;
}
 
bool txt_read()
{
ifstream ifs(“abc.txt”, ios::in);
if (!ifs) return false;
 
/*
char buf[1024];
getline 方式, 读取不包含换行
while (ifs.getline(buf, 1024), !ifs.eof())
{
cout << buf << endl;
}
*/
 
// get 方式
char ch;
while (ifs.get(ch), !ifs.eof())
{
cout << ch;
}
 
ifs.close();
return true;
}
 
int main(int argc, char* argv[])
{
//txt_write();
txt_read();
return 0;

}

以上只介绍了一些简单的读写操作,更多的方法可以参考 fstream 的其他成员方法。 【操作二进制文件】

#include
#include
#include
 
using namespace std;
 
struct Student
{
char name[100];
int num;
int age;
char sex;
};
 
bool file_write()
{
Student s[3] = {
{“dengjia”, 1001, 18, ‘f’},
{“jiadeng”, 1002, 21, ‘m’},
{“beijing”, 1003, 22, ‘f’}
};
 
ofstream ofs(“student.data”, ios::out ios::binary);
if (!ofs) return false;
 
for (int i = 0; i < 3; i++)
{
// 将每个结构体的首地址指针传递给write
// 它会根据你第二个参数给出的大小读取并写入数据到文本。
ofs.write((char*)&s[i], sizeof(s[i]));
}
 
ofs.close();
return true;
}
 
bool file_read()
{
Student s;
ifstream ifs(“student.data”, ios::in ios::binary);
if (!ifs) return false;
 
while (ifs.read((char*)&s, sizeof(Student)), !ifs.eof())
{
cout << s.name << endl;
cout << s.age << endl;
cout << s.num << endl;
cout << s.sex << endl;
}
 
ifs.close();
return true;
}
 
int _tmain(int argc, char* argv[])
{
// file_write();
file_read();
return 0;

}