I finished reading my c++ book and the tutorial in this website. both had similar contents but none tackled the problems I am facing and am still struggling to make the I/O functions with files work as they should.
the example file "example.txt" has the following lines, size of file=47 bytes
1 2 3
|
first sentence
second sentence
third sentence
|
my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream myfile("example.txt",ios::app);///no use of ios::trunc as without declaring it,
// previous content is deleted & replaced by blank file///same
///effect by ios::ate
cout<<myfile.tellp()<<endl;///result was '0'
myfile.seekp(24, ios::end);
cout<<myfile.tellp()<<endl;///result was '71'
myfile<<"should add this text from 71 but text is added from 47, end of file ";//but still writes from 47 which is the
/// end of file while the tellp says should write from 71
}
|
question are in comment. still for better description:
1. if i just use
ofstream myfile("example.txt");///no ios::app
the previous content of file is deleted just by running this line, as if "ios::trunc" was its default parameter but c++ tutorial didn't say anything about it.
2. kind of similar effect with "ios::ate". tutorial said using it would set the writing position to the end of file but using it deleted previous content of file, same effect as in Q)1.
3. using the above code, using
myfile.seekp(24, ios::end);
changed the seek position to "71". but when i tried to add the text, it was added from end of file whose position was 47. how can i add add text to existing file from desired position without deleting previous contents? above code is my shot at doing it, it obviously didn't work out.
NOTE: i deliberately tried to be as much verbose as i could for better description of the problem, because i have finished a book and seriously this is the most confusing chapter in C++ that i have encountered. waiting for responses.