C++ 为什么我的文件在我重新启动程序时被截断?

标签 c++ visual-c++

我正在尝试使用此代码从文件中读取并将值存储在 vector 中。这只工作一次并正确显示所有内容。

void SongList::LoadSongsFromFile()
{
    song temp;
    string line;
    ifstream myFile("SongListFile.txt");
    while (getline(myFile, line)) {
        myFile >> temp.title;
        myFile >> temp.artist;
        myFile >> temp.genre;
        songs.push_back(temp);
    }
}

然后我想附加到文件中,使用以下内容:

void SongList::AddSong(song tmp)
{
    cout << "Enter the title, artist then genre of the song, each on a new line.\n";
    cin >> tmp.title;
    cin >> tmp.artist;
    cin >> tmp.genre;
    songs.push_back(tmp);
    ofstream myFile("SongListFile.txt");
    myFile.open("SongListFile.txt", ios::app);
    myFile << tmp.title << " " << tmp.artist << " " << tmp.genre;
    cout << tmp.title << " by " << tmp.artist << " is now a part of the song library! ";
}

一切正常,但一旦我完成程序,文件将被删除并且没有任何内容,即使我试图附加到文件。明确地说,每次重新打开程序时,我都需要以前的内容和添加的新行。

最佳答案

std::ofstream myFile("SongListFile.txt"); 打开文件并截断​​。你应该使用 std::ofstream myFile("SongListFile.txt", std::ios::app);

否则,您可以使用 std::ofstream myFile; 声明 myFile 对象,然后使用它和附加选项打开一个文件:myFile.open("SongListFile.txt", std::ios::app);

关于C++ 为什么我的文件在我重新启动程序时被截断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43413471/

相关文章:

在 header 中声明的 C++ 外部数组在 main.cpp 中不可用

c++ - C++ 单元测试工具的建议

c - memcpy() 和 memset() 的奇怪行为

c++ - 如何创建一个新的二进制文件并用常量值填充它?

c++ - 如何在 C 或 C++ 中从命令行读取多行输入?

java - 使用 JNI 读取带偏移量的内存

c++ - 谁能帮我写这个简单的素数程序,我做不对

c++ - 自定义开关功能中的大量神秘错误

c++ - 如何找到内存泄漏的位置?

c++ - DLL 导出 : not all my functions are exported