PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to read just before EOF from a file and put it into a string?

 October 30, 2022     c++, eof     No comments   

Issue

My function reads a file and puts it into a string in order for me to process it. I need to read just before EOF, obviously. The problem is that the EOF character is also put inside the string and I can't find a way to bypass it, since it leds other parts of the program to fail. I link the function below.

    string name_to_open, ret = string();
    ifstream in;

    getline(cin, name_to_open);
    in.open(name_to_open.c_str());
    if (!in.is_open()) {
        cout << "Error." << endl;
        return string();
    }
    else {
        ret += in.get();
        while (in.good()) {
            ret += in.get();
        };
    };
    in.close();
    return ret;

The function reads fine until the end of the file, then appends EOF and \0. How can I solve the problem? Does the EOF character work fine in controls? I also tried to put a line ret[ret.size() - 1] = '\0'; at the end of the cycle, but this doesn't seem to work either.


Solution

ret += in.get(); appends the character read from the tile to the string whether the value read was good or not. You need to 1) read, 2) test that the read is valid and the value read is safe to use, 3) use the value read. Currently your code reads, uses, and then tests whether or not the value read was safe to use.

Possible solution:

int temp;
while ((temp = in.get()) != EOF) // read and test. Enter if not EOF
{
    ret += static_cast<char>(temp); // add the character
};

Note: get returns an int, not a char. This is to be able to insert out-of-band codes such as EOF without colliding with an existing valid character. Immediately treating the return value as a char could result in bugs because a special code may be mishandled.

Note: there are many better ways to read an entire file into a string: How do I read an entire file into a std::string in C++?



Answered By - user4581301
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing