Is my fstream bad or bad ()?

So, I have a .cpp file with a function that gets the file name, and should return a String with the contents of the file (the actual contents changed, I changed the code to make it more understandable, but this does not have any effect on my problem). The problem is that it f.good()returns false, and the loop that reads the file does not work. THE CODE:

#include "StdAfx.h"
#include "Form21.h"
#include <string>
#include <fstream>
#include <iostream>



    string ReadAndWrite(char* a){
    char filename[8];
    strcpy_s(filename,a);
    string output;
    char c;
    ifstream f(filename,ios::in);
    output+= "Example text"; // <-- this writes and returns just fine!
    c = f.get();

    while (f.good())
      { 

    output+= c;
    c= f.get();         
          }

    return output;
}

Does anyone have an idea why this is happening? Whether this has anything to do with this is a separate .cpp file (it doesn't even throw an error when deleting #include <fstream>). Maybe there is another way to create a loop? I will be very happy to hear any suggestions on how to fix this, or perhaps another method, how to achieve my goal.

+3
source
3

-, , - . -, while (stream.good()), while (!stream.bad()), while (stream) .. . , , , .

. . , , :

string readfile(std::string const &filename) { 
    std::ifstream f(filename.c_str());   
    std::string retval;

    retval << f.rdbuf();
    return retval;
}

( ) , . ifstream::read , - :

std::string readfile(std::string const &filename) {
    std::ifstream f(filename.c_str());

    f.seekg(0, std::ios_base::end);
    size_t size = f.tellg();

    std::string retval(size, ' ');
    f.seekg(0);
    f.read(&retval[0], size);
    return retval;
}

: ( ), . - , . ( ) - - std::transform , :

struct character_processor { 
    char operator()(char input) { 
        // do some sort of processing on each character:
        return ~input;
    }
};

std::transform(std::istream_iterator<char>(f),
               std::istream_iterator<char>(),
               std::back_inserter(result),
               character_processor());
+4

, strlen (a) 7... filename , .

, :

string ReadAndWrite(string a) {  // string here, if you are into C++ already
    string filename;  // also here
    filename = a;  // simpler
    string output;
    char c;
    ifstream f(filename.c_str());  // no need for ios::in (but needs a char *, not a string
    output+= "Example text"; // <-- this writes and returns just fine!
    f >> c;  // instead c = f.get();

    while (f) // no need for f.good())
      { 

        output+= c;
        f >> c; // again, instead c= f.get();         
      }

    return output;
}
0

All Articles