Home > Software engineering >  How to read a file and write it on a string c
How to read a file and write it on a string c

Time:06-06

I found a solution but I believe there are better ways to do it. How can I improve my code without using complicated tools?

string Read(string& file) {
    ifstream in;
    string text;
    string s;
    in.open(file, ios::in);
    try {
        while (!in.eof()) {
            text.append(s);
            in >> s;
        }
    }
    catch (exception& ex) {
        cout << ex.what();
    }
    in.close();
    return text; 
}

CodePudding user response:

The loop

while (!in.eof()) { 
    text.append(s);
    in >> s;
}

is wrong, because the condition while (!in.eof()) may be false even when the previous statement in >> s succeeded. It would be better to write while (!in.fail()) instead of while (!in.eof()).

However, it would be clearer and slightly more efficient to write the loop like this:

while ( in >> s ) {
    text.append(s);
}

This loop condition indirectly uses in.operator bool(), which is equivalent to !in.fail().

The reason why this loop is a bit more efficient than the other loop is that in the first iteration of the other loop, an empty string was always appended. This is no longer the case in this loop.

CodePudding user response:

Your code reads whitespace-separated words, discards the whitespace, and concatenates all words into one string with no whitespace. You probably want to read the file content verbatim.


One way to read an entire file into a std::string without a loop is to use std::string constructor which takes two iterators - the constructor does the loop for you. Invoke it with std::istreambuf_iterator:

#include <string>
#include <fstream>
#include <iterator>
#include <stdexcept>

std::string read(std::string filename) {
    std::ifstream file(filename, std::ios_base::binary | std::ios_base::in);
    if(!file.is_open())
        throw std::runtime_error("Failed to open "   filename);
    using Iterator = std::istreambuf_iterator<char>;
    std::string content(Iterator{file}, Iterator{});
    if(!file)
        throw std::runtime_error("Failed to read "   filename);
    return content;
}

CodePudding user response:

The simplest way (which often times means the best way) is to read the file one character at a time

string text;
char ch;
while (file.get(ch))
    text  = ch;
  • Related