Search code examples
c++ofstream

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


Its not appending to the end of the already created text file (which has contents in it) that i specify with cin , even when i have out2.open(tablename2, std::ofstream::out | std::ofstream::app); and out2 << v2[i]; in there.

Full code:

#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;
}

Any ideas why?


Solution

  • The constructor already opens the file, although not in appending mode. It's not clear to me what this does (I looked at http://en.cppreference.com/w/cpp/io/basic_filebuf/open , which didn't help too much, and I'm not a standards wizard). If your constructor looks like

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

    and you remove the out.open(....) call, your code works (tested with gcc 4.8.4 - I removed the #include "stdafx.h").