文件读写操作
文件读写操作
实现文件读写操作,了解文本文件的分类,掌握写操作、读操作、读写操作。
文本文件按字符存储,人类可读;二进制文件存字节序列,四级以文本为主。C++ 常用 <fstream>:ofstream 写、ifstream 读、fstream 读写。打开后检查 is_open(),用 <</>> 或 getline 处理内容,结束 close()。
GESP 四级可能考:打开模式 ios::in/out/app、读不到文件时程序应如何处理、逐行读与格式化读的区别。编程题若要求「读入 n 个数求和」,结构往往是 open → 循环读 → 计算 → close。
ifstream fin("data.in");
int x, sum = 0;
while (fin >> x) sum += x;
fin.close();
文件路径错误是常见失分点;本地调试时确认文件名与工作目录一致。
关于下面 C++ 程序的描述,( )最准确。
ifstream in("data.txt");
string line;
while (getline(in, line)) {
cout << line << endl;
}
下面 C++ 代码实现将 Hello 写入 data.txt。
ofstream out("data.txt");
out << "Hello";
out.close();
以下代码将 Hello 写入文件 data.txt。
ofstream file("data.txt");
cout<<"Hello"<< endl;
file.close();
执行下面 C++ 程序,会输出( )。
int main() {
ofstream fout("test.txt");
fout << "Happy" << endl;
fout << "New Year";
fout.close();
ifstream fin("test.txt");
string s1, s2;
fin >> s1;
getline(fin, s2);
fin.close();
cout << s1 << "|" << s2;
return 0;
}
执行下面代码会输出 100。
int main() {
ofstream fout("data.txt");
fout << 10 << " " << 20 << endl;
fout << 30 << " " << 40;
fout.close();
ifstream fin("data.txt");
int a, b, c, d;
fin >> a >> b >> c >> d;
fin.close();
cout << a + b + c + d;
return 0;
}
下面程序能够把 Hello 写入 data.txt 文件中。
ofstream fout("data.txt");
cout << "Hello";
fout.close();
小杨正在读取“冒险日志”文件 quest.txt。若文件内容为 Level 10,执行以下程序后输出为( )。
ifstream fin("quest.txt");
string s;
int v;
fin >> s >> v;
cout << s.length() * v;