c++ - 为什么没有任何内容写入文本文件?

标签 c++ output ofstream

我正在尝试将歌曲信息写入文本文件,但没有写入任何内容。我试图将信息写入 onF 的部分正在运行,但文件为空。顺便说一句,下面的代码是递归函数的一部分,这是前几个 if 语句的原因。有什么想法吗?

void writeToFile(int artist, int album, int song, int nA, int nAl, int nS)
{    
    ofstream onF("library.txt");
    if(song>=nS)
    {
        album+=1;
        song = 0;
    }
    if(album>=nAl)
    {
        artist++;
        album = 0;
        song = 0;
    }
    if(artist>=nA)
    {
        onF.close();
        return;
    }
    if(onF.is_open())
    {
         onF<<artists[artist].artistName<<'#';
         onF<<artists[artist].albums[album].albumName<<'#';
         onF<<artists[artist].albums[album].songs[song].songName<<'#';
         onF<<artists[artist].albums[album].songs[song].songLength<<endl;
         cout<<"RAN"<<endl;
    }
    else
        cout<<"File could not be opened."<<endl;
    song++;
    int numAlbums = artists[artist].numAlbums;
    int numSongs = artists[artist].albums[album].numSongs;
    writeToFile(artist, album, song, nA, numAlbums, numSongs);
 }

现在我已经开始工作了,但我无法从文件中加载信息。它加载了两次歌曲信息,第二次加载了除了歌曲标题之外的所有内容。循环运行两次:

if(inF)
{
    while(!inF.eof())
    {
        getline(inF, newArtist, '#');
        getline(inF, newAlbum, '#');
        getline(inF, newSong, '#');
        inF>>songLength;
        cout<<"CALLED"<<endl;
        addSong(newArtist, newAlbum, newSong, songLength, numArtists, 0, 0);      
    }
    inF.close();
    if(inF.is_open())
        cout<<"FAILED TO CLOSE"<<endl;
}

最佳答案

您在函数入口处截断文件,因此最后一次调用将清除所有已写入的内容。

如果要附加,请添加 std::ios::app 标志

关于c++ - 为什么没有任何内容写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27333805/

相关文章:

python - python 有选择地抑制输出

C++ ofstream输出到图像文件在Windows上写入不同的数据

c++ - 使用 ofstream 将整数作为十六进制写入文件

c++ - C++如何使用fstream修改文件

c++ - 如何等待两个pthreads?

c++ - 如何设置 Win32 richedit 的上/下边距

Java - 在循环中打印逗号

c++ - 四元数 FFT 在 C++ 中使用一维 FFT

c++ - 自定义 Windows GUI 库

java - 在java中输出图像