What's Preferred Pattern for Reading Lines from a File in C++

What's preferred pattern for reading lines from a file in C++?

while (std::getline(fs, line))
{}

This is not only correct but preferable also because it is idiomatic.

I assume in the first case, you're not checking fs after std::getline() as if(!fs) break; or something equivalent. Because if you don't do so, then the first case is completely wrong. Or if you do that, then second one is still preferable as its more concise and clear in logic.

The function good() should be used after you made an attempt to read from the stream; its used to check if the attempt was successful. In your first case, you don't do so. After std::getline(), you assume that the read was successful, without even checking what fs.good() returns. Also, you seem to assume that if fs.good() returns true, std::getline would successfully read a line from the stream. You're going exactly in the opposite direction: the fact is that, if std::getline successfully reads a line from the stream, then fs.good() would return true.

The documentation at cplusplus says about good() that,

The function returns true if none of the stream's error flags (eofbit, failbit and badbit) are set.

That is, when you attempt to read data from an input stream, and if the attempt was failure, only then a failure flag is set and good() returns false as an indication of the failure.

If you want to limit the scope of line variable to inside the loop only, then you can write a for loop as:

for(std::string line; std::getline(fs, line); )
{
//use 'line'
}

Note: this solution came to my mind after reading @john's solution, but I think its better than his version.


Read a detail explanation here why the second one is preferable and idiomatic:

  • Linux | Segmentation Fault in C++ - Due to the function ifstream

Or read this nicely written blog by @Jerry Coffin:

  • Reading files

How to search a pattern in a file using c skills? or how to read line on line from a file in c?

Yes it is possible, you can do pretty much anything in C. Open the file, read it character by character (byte by byte), check if it is the first letter in your search key ('h'), if it is, check if it is the next letter and so on.

EDIT: Pseudo code

const char key[] = "hello";
bool found_key = false;

open file
handle errors if not open

while not end of file
{
i=0;
do
{
ch = read 1 character;

if(ch == key[i])
{
if(i==sizeof(key))
{
found_key = true;
break;
}
i++;
}
} while(ch == key[i]);
}

I would regard any solution involving saving more than 1 char in RAM as quite suspicious.

How to read complex text file in c++?

Instead of mangling your file until you can read it, you should look closely at the grammar that defines your file format and build a small parser. While the task may look daunting at first, it is not that difficult.

I prefer Boost.Spirit for such tasks.

Recommended ways to read certain things in a text file

If your input file structure is static that means it wont change the order; you can use the below instead of your //ReadLines code.

        var allLines = File.ReadAllLines(path);
var dataSet = allLines.Select(line => line.Trim().Split(' ')[1]).ToArray();
// Add conditional checks regarding the length of the dataset and any thing else.
var userName = dataSet[0];
var accesscode = Convert.ToInt32(dataSet[1]);
var value = Convert.ToInt32(dataSet[2]);
var email = dataSet[3];

// Then your console.writeline statements here.

If you are unsure of the order, you can use dictionary to store the both parts of line split one for key and other for value. And then print them.



Related Topics



Leave a reply



Submit