seekg = sekkp ? :|

Hello !
I read about seekg and seekp,but i didn't understood what they do....
I've tryed this both codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>

using namespace std;
int main() {
	
	fstream f("file.txt",ios::out); 
	
	f.seekp(5);
	//f.seekg(5);
	f<<"write";
	f.close();
	
	system("pause");
	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>

using namespace std;
int main() {
	
	fstream f("file.txt",ios::out);
	
	//f.seekp(5);
	f.seekg(5);
	f<<"write";
	f.close();
	
	system("pause");
	return 0;
}


Both work(no error),and the result are exact the same :|
In file.txt is written "abcdefgh12345678",and after compiling,is written:
[NUL][NUL][NUL][NUL][NUL]write.
I would be happy for any response :)
Thank you,and Merry Christmas !
Last edited on
I believe

 
ios::out


Creates an output file that is blank so you will always create a blank file and then move forward 5 and write on the sixth space. Since you never created values for the data positions before where you placed the cursor the [nul] is not at all unexpected.

If you were wanted to write to the file but not create a blank document I think you need to use
 
ios::out | ios::in


This shouldn't call the Truncation
thank you,it worked with ios in and ios out.
This is important to know:
1
2
f.seekg(5); // move the "get" position forward
f<<"write"; // write at the "put" position 

This writes at the 6th positions, because file streams have only ONE position. Both reading and writing happen there. That's a limitation of the C file I/O, which C++ file I/O is implemented in terms of.

Other C++ streams (stringstream for example) have two independent positions: one for reading, one for writing. If f is a stringstream, your f<<"write" will write starting at the first position, where the put pointer is.
Last edited on
ok,i understood:
But here is another problem.
I realized that seekg has influence on seekp and viceversa.Here is my example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>

using namespace std;
int main(){
	
	fstream file("file.txt",ios::in|ios::out);
	
	
	file.seekp(2);
	file.seekg(6);
	cout<<file.tellp()<<","<<file.tellg();

	
	
	
	


	cin.ignore();
	return 0;
}

The output is 6,6.If i use seekg(6) before seekp(2),the output will be 2,2 .
Is this normally ? :|
Yes, this is what file streams do. They have only one position, both seekp() and seekg() move it.
Compare to:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <sstream>

using namespace std;
int main(){

    stringstream stream("some text");
    stream.seekp(2);
    stream.seekg(6);
    cout << stream.tellp() << "," << stream.tellg() << '\n';
}

this prints 2,6
Topic archived. No new replies allowed.