Domanda

I am new to c++. I made the following program which runs successfully and does its intended job which is to append the data of one file to another file.

#include<iostream>
#include<fstream>
#include<stdio.h>

using namespace std;

void show(const char *file)
{
  char data[90];
  fstream f(file,ios::in);
  while(!f.eof())
  {
    f.getline(data,90,'\n');
    puts(data);
  }
}
int main()
{
  char data[90];
  cout<<"Contents of files before data integration.\nFile 1:\n";
  show("file1.txt");
  cout<<"\nFile 2\n";
  show("file2.txt");
  fstream f1("file1.txt",ios::out|ios::app);
  fstream f2("file2.txt",ios::in);
  while(!f2.eof())
  {
    f2.getline(data,90,'\n');
    f1<<data<<'\n';
  }
 cout<<"\n\nFile 1 after data integration: \n\n";
 show("file1.txt");
}

As i checked separately the file appends the data in file1 successfully but the program prints only its old contents. Can anyone tell me what could be the possible reason for that and the remedy for the same.

È stato utile?

Soluzione

Until the stream f1 is closed, the contents that have been written to it may reside in a buffer. If this happens, the last call to show will display the old contents of the file or (maybe worse) an incomplete version of the new contents.

Flushing could do the trick, as Ed Heal suggests in his answer, but I think that the proper way to do this is to close stream f1 as soon as the writing finishes. (Same for f2, if you like.) Add the following lines just after the while loop and before the last call to show:

f1.close();
f2.close();

Altri suggerimenti

If is buffering it.

Flush the stream and the smell of the old file goes away.

See http://www.cplusplus.com/reference/ostream/ostream/flush/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top