Vineeth B V
Vineeth B V

Reputation: 75

Unable to retrieve file data from file in turbo c program

Ok, now I'm trying out a very basic program in turbo c / DOSBOX using filestream. What I've noticed is that my ofstream variable works properly while writing data into the file, but the problem is in retrieving the data. The ifstream variable isn't working properly for some reason, or the method used here to retrieve the file data maybe improper. If you can help me out with this, please contact me.

This is my code:-

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<fstream.h>
void main()
{
   char user[20],pin[10];
   ofstream fout("TEMP");
   ifstream fin("TEMP");
   clrscr();
   fin>>user;
   cout<<"Username : "<<user;
   cout<<"\nEnter username.\n";
   gets(user);
   cout<<"Enter pin.\n";
   cin>>pin;
   fout<<"Username : "<<user<<endl<<"Pin : "<<pin;
   cout<<"\nUsername : "<<user;

   getch();
}

The data I entered is : Username = dragonis. pin = 123.

Everything is stored perfectly in the file. But when retrieving, there is no output of username when cout is given at the beginning of the program. It is blank.

Upvotes: 2

Views: 552

Answers (1)

Sneftel
Sneftel

Reputation: 41503

The issue here is likely the fact that you're opening the same file twice at the same time. This will almost certainly fail, putting fin in a bad state and causing your extractions to fail without doing anything.

It's not clear what you're trying to accomplish here -- currently you only read a single word from the file (a username which you display and then discard), and you write data of a different format, hopefully overwriting the old data. But if that's actually what you're trying to do, you should make the lifetimes of fin and fout not overlap, so that the file is closed before reopening:

   char user[20],pin[10];
   {
       ifstream fin("TEMP");
       clrscr();
       fin>>user;
       cout<<"Username : "<<user;
       cout<<"\nEnter username.\n";
       gets(user);
       cout<<"Enter pin.\n";
       cin>>pin;
   }
   {
       ofstream fout("TEMP");
       fout<<"Username : "<<user<<endl<<"Pin : "<<pin;
       cout<<"\nUsername : "<<user;
   }

Since a local variable is destroyed when it goes out of scope, this guarantees that the file is closed for reading before it is reopened for writing.

You could also open it as an fstream, which supports both input and output, but I get the feeling you're already not doing what you're trying to do, so I think keeping input and output separate would be for the best.

Upvotes: 2

Related Questions