Hi!
I am in a confusion that either get and put pointers are the same or not. I tried to understand them with a little snippet of code [given below], but it boosted up my confusion :p .
What this code does.
Lets say, i have a file "textfile.txt" containing the following text.
Now the file is opened with fstream in both input and output mode.
Initially the file pointer is at beginning, so tellp() and tellg() both returning "0".
Then I write into the file // file<<"Nouman";
Now the pointer moves to pos 6 and both tellp and tellg return "6".
Now after putting text into the file, both get and put pointers are at 6, now i want to read from pos 6 as get pointer is also at 6, using // file>>name;
But,
Instead of reading from pos 6 it writes some garbage characters from 6 onward.
ignoring the fact that i have my get pointer at 6 and there is some data available to be read. :@
Also, after writing this garbage, both tellp and tellg return "-1" what is it...
Here Goes The Code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
int main()
{
fstream file("textFile.txt", ios::in | ios::out);
if( file.fail() ) // File doesnot exists. create it...
{
cout<<"No such file exists.\n";
cout<<"Creating file \'textFile.txt\'.\n";
ofstream newFile("textFile.txt");
if( newFile.fail() ) // File is not created successfully
cout<<"Error creating New file.\n";
else // File created successfully...
{
cout<<"A file \'textFile.txt\' has been created successfully.\n";
newFile<<"Shahid\nKamran\nLuqman\n";
newFile.close();
}
}
else // File already exists and is opened. use it
{
char name[20];
cout<<"get pointer at: "<<file.tellg()<<endl;
cout<<"put pointer at: "<<file.tellp()<<endl;
file<<"Nouman";
cout<<"get pointer at: "<<file.tellg()<<endl;
cout<<"put pointer at: "<<file.tellp()<<endl;
file.getline(name,20);
cout<<"get pointer at: "<<file.tellg()<<endl;
cout<<"put pointer at: "<<file.tellp()<<endl;
cout<<"data read is: "<<name<<endl;
file.close();
}
return 0;
}
|