samedi 31 octobre 2015

Converting file to char* Issue

I am a beginner at C++ programming, and I encountered an issue. I want to be able to convert the contents of a file to a char*, and I used file and string streams. However, it's not working.

This is my function that does the work:

char* fileToChar(std::string const& file){

    std::ifstream in(file);
    if (!in){
        std::cout << "Error: file does not exist\n"; 

    std::stringstream buffer;
    buffer << in.rdbuf() << std::flush;

    return const_cast<char *>(buffer.str().c_str());

However, when I test the method out by outputting its contents into another file like this:

std::ofstream file("test.txt");
file << fileToChar("fileTest.txt");

I just get tons of strange characters like this:


What exactly is going on here? Is there anything I missed? And if there's a better way to do this, I would be glad to know!

Aucun commentaire:

Enregistrer un commentaire