0

I have the following block of code that i am using to read a text file of the following format:

firstname lastname id mark
firstname lastname id mark

Following is the block of code.

void DBManager::ReadFile(void){
fstream myfile; /*fstream object that will be used for file input and output operations*/
char* fn;       /*pointer to the storage which will hold firstname*/
char* ln;       /*pointer to the storage which will hold lastname*/
int id;         /*integer var to hold the id*/
float mark;     /*float var to hold the mark*/

/*read in the filename*/
g_FileName = new char[1024];                /*allocate memory on the heap to store filename*/
cout << "Please enter the filename:";
    cin >> g_FileName;

/*open file*/
myfile.open(g_FileName, ios::in | ios::out);

if(myfile.is_open()){   /*check if the file opening is successful*/
    cout << "File reading successful !\n";

    /*read information from the file into temporary variables before passing them onto the heap*/
    while (!myfile.eof()) {

        fn=(char*) new char[1024];
        ln=(char*) new char[1024];
        myfile >> fn >> ln >> id >> mark;
        cout << fn << " " << ln << " " << id << " " << mark << " " << endl;

    }
    myfile.close();
}
else{                   /*else print error and return*/
    perror("");
    return;
}

}

The above block of code works ! :) But I am surprised as to how myfile knows it is supposed to hold one line at a time and how its being smart enough about setting the four variables.

I am new to C++ , and hence this might be covered in some sort of documentation. But i would be happy to have some insight from you'll or a link to somewhere i can understand fstream objects better.

2 Answers 2

2

In C++, std::fstream is a type of stream which works specifically for files. When reading from a file, the interface for std::fstream is almost identical to std::cin. Input streams are programmed to read the next word or number when asked with the >> operator. They know where words and numbers are because they are separated by white space. In the default locale, spaces, tabs and newlines are considered to be white space. You can change the locale to include other characters, like commas, and have those be skipped while reading from a file. Basically, when reading with input streams, newlines and spaces are treated the same.

Some nice explanation for learning about streams is here: http://www.cprogramming.com/tutorial/c++-iostreams.html

2

I'm not sure what the question is. However, the code has several problems:

  1. You should always check input after having tried to read.
  2. Testing for eof() to determine if there is more to read doesn't work.
  3. You have a memory leak, allocating memory in every iterator.
  4. Reading without a constraint into a char array is unsafe, i.e., it is prone to buffer overrides (one of the major attack vectors).

You want to use a loop looking something like this:

std::string fn, ln;
while (myfile >> fn >> ln >> id >> mark) {
     ...
}
7
  • Hi Dietmar, basically i am not sure how my code works .. is myfile automatically configured to hold one line at a time ? Oct 16, 2012 at 20:53
  • The input doesn't really care about lines but reads the four values into variables and holds them. If the values happen to split across lines it would still do the same thing. Note, that the separators of your values used are spaces, i.e. you name forename and the last name can't contain any spaces. Oct 16, 2012 at 21:03
  • thanks Dietmar ! i see whats happening now. Thanks for your suggestions... As its for a school assignment we dont have to worry about 1 and 4. But we have been asked to worry about memory leaks i am calling a constructor to create a student object with these temp vars at end of each iteration . so there is no leak . as i pass the pointers to first and lastname into the constructor .. regarding 2. why wont checking for eof() work ?? Oct 16, 2012 at 21:21
  • If you skip 1. you'll end up sort of processing the last line twice! You enter the loop at the end of the file and won't read anything new which normally appears as if the last line is processed twice. With respect to the pointer, I strongly recommend not to use pointers but use, e.g., std::string instead. With respect to eof(): it may never get set if any of the inputs is invalid, providing an infinite loop. It is generally wrong to use eof() for loop controls. At the very least you would need to make sure that you skipped any trailing spaces. Oct 16, 2012 at 21:37
  • hmm ok i see your point with eof() maybe i should check that with good() i have to use char* .. not allowed to use string (school work !) i still dont get what you are trying to point out with 1. .. can u provide an example ? Oct 16, 2012 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.