0
file.open(input_file);
char z;
while(file.get(z))
{
    str1 = str1 + z;
    pos1++;
} 
file.close();
fout.open(output_file , ios :: app);
file.seekg(0,ios::beg) ;
fout<<endl;
fout<<str1;
fout.close();

file.open(output_file);
file.seekg(0,ios::beg);

char y;
while(file.get(y))
{
    cout<<y;
}
file.close();
cout<<endl;

In the above code, I have used seekg and std::ios::app function but it adds the input text file at the end of output text file. How do I add it at the beginning?

Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39

1 Answers1

0

Not tested, but I get:

file.open(input_file);
char z;
while(file.get(z))
{
    str1 = str1 + z;
    pos1++;
} 
file.close();
fout.open(output_file , ios :: app);
char y;
while(file.get(y))
{
    fout<<y;
}
fout<<endl;
fout<<str1;
fout<<endl;
file.close();

For some dumb reason, OS's almost never provide means to prepend a file, I suppose thinking to prevent half-empty sectors; so you must re-write it all. Also, you might want to limit the amount of input, so as to not cause a buffer overflow security risk or memory access crash. Also, block I/O is much faster.

CodeLurker
  • 1,248
  • 13
  • 22
  • The dumb reason: It's inefficient as hell. When you give people an easy way to do something inefficient, they have an annoying tendency to do it and then whine about the poor performance. – user4581301 Nov 29 '21 at 04:49
  • One could have a primitive to write the front; and then when you close it, the rest is appended. In some cases, it might be faster. There is vector::push_back() and vector::insert() after all. Who knows what optimizations might be possible, depending on the buffering and sector structure. – CodeLurker Nov 29 '21 at 04:53
  • thank you guys , I got how to do it !! – crazy_coder1905 Nov 29 '21 at 14:23