ofstream不写入c ++中现有文本文件的末尾

ofstream not writing to end of existing text file in c++

它不会附加到我用 cin 指定的已创建文本文件(其中包含内容)的末尾,即使我有 out2.open(tablename2, std::ofstream::out | std::ofstream::app);out2 << v2[i];那里。

完整代码:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>  
#include <iomanip>
#include <stdio.h>

using namespace std;
using std::vector;
using std::string;

void insertit(std::vector<std::string>& v, std::vector<std::string>& v2, std::string insertedstr) 
{
    std::string tablename2;
    cout << "Enter file name with the extension " << endl;
    std::getline(std::cin, tablename2);
    for (int w = 0; w < v.size(); w++) {
        cout << v[w] << ": ";
        cin.ignore();
        std::getline(std::cin, insertedstr);
        v2.push_back(insertedstr + " ");
        insertedstr.clear();
    }

    //below, why is it not writing to the file you specified from cin >>tablename2?
    std::ofstream out2(tablename2);
    out2.open(tablename2, std::ofstream::out | std::ofstream::app);

    for (int i = 0; i < v2.size(); i++) {
        out2 << v2[i];
    }

    out2.close();
    v2.clear();
    cout << "The record has been inserted into " << tablename2 << endl;
}

int main() 
{
    std::vector<std::string> v = {"author", "title"};
    std::vector<std::string> v2;
    std::string insertedstr;

    insertit(v, v2, insertedstr);

    return 0;
}

知道为什么吗?

构造函数已经打开文件,但不是在附加模式下。我不清楚这是做什么的(我查看了 http://en.cppreference.com/w/cpp/io/basic_filebuf/open ,这并没有太大帮助,而且我不是标准向导)。如果你的构造函数看起来像

std::ofstream out2(tablename2, std::ofstream::out | std::ofstream::app);

并且你删除了 out.open(....) 调用,你的代码有效(使用 gcc 4.8.4 测试 - 我删除了 #include "stdafx.h")。