fstream没有写入文件

时间:2013-02-27 02:36:10

标签: c++ fstream

当fstream位于特定位置时,我无法写入我的文件。在下面的代码中,当注释行被取消注释时,文件被写入,但是当它被注释时,文件根本不被写入。我添加了一堆控制台输出,它表示“outputFile<< newWord<< endl;”周围的两个输出已完成但文件从未实际写入。

void write_index( string newWord )
{
fstream outputFile( "H:\\newword.txt", ios::app );
int same = 0;
string currWord;
currWord.resize(5);
//outputFile << newWord << endl;
while( !outputFile.eof() )
{
    getline( outputFile, currWord );
    cout << "Checking if " << newWord << "is the same as " << currWord << endl;
    if( newWord == currWord )
    {
        cout << "It is the same" << endl;
        same = 1;
        break;
    }
}
if( same != 1 )
{
    cout << "Writing " << newWord << "to file" << endl;
    outputFile << newWord << endl;
    cout << "Done writing" << endl;
}
outputFile.close();

}

1 个答案:

答案 0 :(得分:2)

我有点相信你正在寻找这些方面的东西:

void write_index( const string& newWord )
{
    fstream outputFile( "H:\\newword.txt", ios::in);
    bool same = false;

    if (outputFile)
    {
        string currWord;
        while (getline(outputFile, currWord))
        {
            cout << "Checking if " << newWord << " is the same as " << currWord << endl;
            same = (newWord == currWord);
            if (same)
            {
                cout << "It is the same" << endl;
                break;
            }
        }
    }

    if (!same)
    {
        outputFile.close();
        outputFile.open("H:\\newword.txt", ios::app);

        cout << "Writing " << newWord << "to file" << endl;
        outputFile << newWord << endl;
        cout << "Done writing" << endl;
    }

    outputFile.close();
}

有更好的方法可以做到这一点,但这可能是一个体面的起点。