首页 > 解决方案 > 为什么我的程序在第一次运行时写入文件,但在以后运行同一程序时却没有?

问题描述

我正在尝试编写写入文件的代码。它适用于第一次运行,但对于以后的任何运行,它都不会将用户输入写入文件。为什么在创建写入文件后不写入文件?我有一个 if-else 语句来检查一个已经存在的文件。如果有一个文件,它应该写入它。否则,它会创建一个要写入的文件。

fstream advice("advice.txt", ios::in|ios::out);
advice.open("advice.txt");

    if (!advice.fail())
    {
        cout << "Found advise file." << endl << "Old advice:" << endl;
        while (getline(advice, line))
        {
            cout << line << endl;
        }
        advice.flush();
        advice.close();
        advice.open("advice.txt", ios::in|ios::out|ios::app);
    }
else
    {
        cout << "Could not open the Advise file." << endl<<"Assumption: first run - creating a new file..."<<endl;
        advice.flush();
        advice.close();
        advice.open("advice.txt", ios::in | ios::out | ios::trunc); //create new file
    }

cout << "Enter your phrase for the next user." << endl;
    getline(cin, line);

    advice <<line << endl;

    advice.flush();
    advice.close();
    return 0;

标签: c++visual-c++

解决方案


推荐阅读