【问题标题】:How to open a file or create it if it doesn't exist and fill it with values from the console如果文件不存在,如何打开文件或创建它,并用控制台中的值填充它
【发布时间】: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;
}

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

【问题讨论】:

    标签: c++ file fstream


    【解决方案1】:

    peek之后文件处于eof状态,不能写入。

    重新设置在开头:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-26
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2014-07-20
      • 2015-10-07
      • 2014-11-09
      相关资源
      最近更新 更多