2

I was writing a -kind of - server that works io thru files. When I tried to append a string to the file, (I at the time did not know about ios::app, so I used a very unconventional way of doing it) it would not behave as I expected ( I tried the append function without the loop, and it worked every time):

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
ofstream* open(string fileName)
{   // opens a file and returns a pointer to the object ready for writing
    vector<string> contents;
    ifstream f(fileName.c_str());
    if (!f)
    {
        cout << "No File Found";
        exit(-1);
    }
    while (!f.eof())
    {   //read
        string temp;
        getline(f, temp);
        contents.push_back(temp);
    }
    f.close();
    ofstream* out = new ofstream(fileName.c_str());
    for (int i = 1; i < contents.size(); i++)
    { // write previous contents
        *out << contents[i] << endl << flush;
    }
    return out;
}
void apend(string text, string fileName)
{
    ofstream* file = open(fileName);
    *file << text << endl << flush; // insert text
    file->close();
}
string stringify(int in)
{ // converts an integer to a string
    stringstream x;
    x << in;
    string out;
    x >> out;
    return out;
}
int main()
{
    cout << "Welcome to the cgs v1.0 ... loading files ... " << endl;
    for (int i = 0; i < 10; i++)
        apend(stringify(i), "server1.txt");
    return 0;
}

Upon running this I got : server1.txt :

5

6

7

8

9

And if I ran the program again : server1.txt:

0

1

2

3

4

5

6

7

8

9

My question is, if I used std::flush why did it somehow not write the whole file, and then when it was re-run, write the rest of the first cycle and none of the second? - This is just curiosity. I will now move to ios::app. Thanks for any explanations.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 1
    Better to do `while(getline(f, temp))` than checking for .eof. (Read: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Arnav Borborah Jan 28 '18 at 21:11
  • I can't explain it either but clearly `for (int i=1; i – john Jan 28 '18 at 21:12

0 Answers0