-1

I am writting a function for my code.
the function only need a opened file to process.

here the code of the function :

void printFile(std::ifstream &file)
{
    file.seekg(0, file.end);
    int length = file.tellg();
    file.seekg(0, file.beg);

    char *buffer = new char[length];
    file.get(buffer, length);
    file.seekg(0, file.beg);
    char c;
    int i = 0;
    std::cout << "Uncreypted file" << std::endl;
    while (file.get(c))
    {   
        // loop getting single characters

        std::cout << c << " " << buffer[i] << " ";
        i++;
    }
    std::cout << std::endl;

    delete[] buffer;
}

the result is weird :

Uncrypted file
t h h i i s s i i s s a a t t e e s s t t
t ═ h ═ i ═ s ═ ═ i ═ s ═ ═ a ═ ═ l ═ i ═ g ═ n ═

after one line the buffer output something different where as file.get.(c) work proprely, why ?
Is this because of the carriage return ascii letter ?

Maximilien Nowak
  • 81
  • 1
  • 1
  • 8
  • 1
    This code broke my heart. Did you read the documentation ? – Stargateur Apr 13 '18 at 10:57
  • 1
    Read the documentation for `get(char *c, int length)`. It does ***not*** just read `length` characters from the input stream. It does something different. You don't need stackoverflow.com to find the documentation for get(). It should be in your C++ book. – Sam Varshavchik Apr 13 '18 at 10:59

1 Answers1

3

after one line the buffer output something different

That's because you did not read the documentation for the functions that you've used.

file.get(buffer, length) stops at the first newline by default (ref).

So, your buffer only contains the first line of the file.
Your other buffer[i] accesses are pulling out nonsense.

Read about how best to read a whole file into a string in C++.

And don't program "blind", then act surprised when your program doesn't do what you wanted;
read the documentation!

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989