在c++中,Ofstream没有写入到现有文本文件的末尾

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

本文关键字:文本 文件 c++ Ofstream      更新时间:2023-10-16

它不附加到我用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")。