seekp() and tellp() (I/O)

hi guys I'm studying and playing around with the filepointer the seekg does exactly what I expected it to do it goes to the offset where you want to position it but the seekp doesn't seem to be working in the way I expected it to,

I have a .txt file and inside it is a string saying my name is adam

when I use the tellp function I expect the pointer to be pointing the after the last character but instead it points to zero

but when when I try to add contents to a random place in the file( seekp(2) )
it just writes it to the end of the file,not sure why

so my goal is to write to a random place in the file


thanks

1
2
3
4
5
6
7
8
9
   ofstream ou;
    ou.open("justFor.txt",ofstream::app);

    cout << "file pointer is at  " << ou.tellp() << endl;

    ou.seekp(2);
    ou << "XX";

    ou.close();
The file is opened in append mode.
oh ok so this is only possible if the append flag is not chosen?

I followed this tutorial on here http://www.cplusplus.com/reference/ostream/ostream/seekp/


but my filePointer always seems to be in position 0 even with append mode off

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

    ofstream ou;
    ou.open("justFor.txt");

    cout << "file pointer is at  " << ou.tellp() << endl;

    ou.write("heyho",5);
    long pos = ou.tellp();
    cout << pos << endl;
    ou.seekp(pos-2);
    ou.write("XX",2);

    ou.close();



in the tutorial I'm following it seems to work for him/her

*edit sorry I jumped the gun a little bit it does seem to be working it just overwrites "ho"

is there anyway to write to a certain position with append mode on?

thanks
Last edited on
is there anyway to write to a certain position with append mode on?

No, ios::app always writes to the end of the file.

Topic archived. No new replies allowed.