【发布时间】:2021-04-05 23:05:47
【问题描述】:
我的目标是编写一个程序来检查文件是否存在以及它是否包含值。如果为真,则程序应将文件中的这些值读取到数组中,如果不存在则创建文件并从控制台将值写入文件。我写下一段代码:
#include <fstream>
#include <iostream>
using namespace std;
int main(void)
{
char filename[] = "alphabet.txt";
string alphabet;
char ch;
bool f;
fstream fileWithAlphabet;
fileWithAlphabet.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
(fileWithAlphabet.peek() == std::ifstream::traits_type::eof()) ? f = true : f = false;
if (f)
{
cout << "File empty, fill file" << endl;
cout << "Fill the file with alphabet characters" << endl;
cout << "please enter a single character, using q to stop: " << endl;
for (;;) {
cin >> ch;
if (ch == 'q')
break;
fileWithAlphabet << ch << "\n";
}
fileWithAlphabet.close();
}
else
{ // use existing file
cout << "success " << filename << " open. \n";
cout << "read from a file";
**** read into array ****
fileWithAlphabet.close();
}
return 0;
}
请说,为什么在控制台执行代码和输出后,文件仍然是空的?
【问题讨论】: