简体   繁体   中英

Writing and reading from a file sequentially using the same file object

I am learning data file handling basics in c++ (and am working in the compiler turbo C++). So I wanted to create a text file , write some data onto it and then read it. So I wrote this: -

int main()
{
fstream fin;
fin.open("textfile.txt",ios::in|ios::out);
for(int i=0;i<3;i++)
{
char x;
cin>>x;
fin<<x;
}
fin.seekg(0,ios::beg); //I added this and also tried seekp() when I didn't get the desired output
                   //but to no use 
while(!fin.eof())
{
char v;
fin>>v;
cout<<v;
}
fin.close();
getch();
return 0;
}

But instead of outputting only the 3 characters which I input, it outputs 4 characters. I tried removing the loops and taking input and giving outputs one by one like this (among other things):

...
char x,y,z;
cin>>x>>y>>z;
fin<<x<<y<<z; 
fin.seekg(0,ios::beg);
char q,w,e;
fin>>q>>w>>e;
cout<<q<<w<<e;
...

But it still didn't work.

I think it has something to do with file pointers and their location but don''t know what. I tried finding a similar question on the net but to no avail.

So I want to know what is wrong with what I did and how to I improve this to actually write and read in a file sequentially using the same file object (if it is even possible). And is seekg() even necessary here?

Thanks.

The problem you face is a general problem. Your input code is right and there is no error in that. The problem is your ouput code and to be more specific the line while(!fin.eof()) . eof(end-of-file) works on a end of file mark whose numeric value is generally -1. But this function goes false only when the end character is encountered and traversed. To remove this error just replace this statement with a read statement that is move this line fin>>v from loop statements to the conditional statements. In this false will be when it encounters a end character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM