0

Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?

I'm a total beginner and I have this function in which I use .eof however I was told that it's not a good idea since that would not work with linux and that I should use .good So could you tell me what I would do and how I should modify it

std::string ex_file_licensing::getUsedLicense(const std::string &FlexLMfileName){

        std::ofstream openFile;
        std::string line;
        std::string tempString;
        std::string testResult;
        size_t start_pos;
        size_t stop_pos;
        std::string retour ="";
        filebuf fb;
        fb.open (FlexLMfileName.c_str(),ios::in);
        istream toOpen(&fb);


        if(toOpen.eof()){
            while(!toOpen.eof()){
                getline(toOpen,line);
                if(line.find("Checkout") != std::string::npos ){   
                    start_pos = line.find(":"); 
                    tempString = line.substr(start_pos+1);
                    stop_pos = tempString.find("/");
                    testResult = tempString.substr(start_pos, stop_pos);
                }
                else if (line.find("FLEXnet") != std::string::npos ){   
                    start_pos = line.find("FLEXnet"); 
                    tempString = line.substr(start_pos+1); 
                    stop_pos = tempString.find("Feature");
                    testResult = tempString.substr(start_pos, stop_pos);
                }
                cout << testResult << endl;
                retour.append(testResult);
            }

            fb.close();
        }

        return retour;
    }
Community
  • 1
  • 1
Samsara
  • 37
  • 1
  • 2
  • 6

2 Answers2

1

Use a loop like this:

while (getline(toOpen, line)) {
   ...
}
sth
  • 222,467
  • 53
  • 283
  • 367
0

Use neither: the stream has a built-in conversion operator to boolean, you can thus test it simply with if (toOpen) or while(toOpen) and it just works.

By the way, your if condition looks wrong as it only executes the code within if the filestream reached the EOF character.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • yep, The if condition is wrong. – Behrooz Jun 06 '12 at 09:53
  • hi so If I put `while(toOpen)` instade of `while(!toOpen.eof())` it would give the same result ? – Samsara Jun 06 '12 at 14:46
  • Not quite, just because the stream is okay before you start consuming does not mean it will stay okay forever. You would need to test after each extraction, which is why @sth recommended `while(getline(...))`. – Matthieu M. Jun 06 '12 at 15:33