如何打开文件或创建文件(如果文件不存在)并用控制台中的值填充它

How to open a file or create it if it doesn't exist and fill it with values from the console

本文关键字:文件 控制台 填充 何打开 创建 不存在 如果      更新时间:2024-05-23

我的目标是编写一个程序,检查文件是否存在以及是否包含值。如果它是真的,程序应该将这些值从文件中读取到数组中,如果不存在,则创建一个文件,并从控制台将值写入文件。我写下一个代码:

#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;
}

请说,为什么在执行代码并从控制台输出后,文件仍然为空?

peek之后,文件处于eof状态,您无法在其中写入。

重新开始设置:

(fileWithAlphabet.peek() == std::ifstream::traits_type::eof()) ? f = true : f = false;
fileWithAlphabet.seekg (0);