-2

Im trying to copy a whole .txt file into a char array. My code works but it retrieves just the last line in the file to be opened. Here is my code, and a big thanks

#include <fstream>
using namespace std;
std::ifstream fileToRead;
unsigned char array[512];   
fileToRead.open("test.txt");
if(fileToRead.is_open()){
    while(!fileToRead.eof()){
        fileToRead >> array;
    }
fileToRead.close();
}
printf("%s\n", array);

2 Answers2

0

You're repetitively reading a line into the start of the array, with no offset to allow for previous content. It therefore always overwrites what the prior read input.

Many OSes let you map a file into an array's address space. That will likely be much faster.

Feldur
  • 1,005
  • 9
  • 21
0

Your just rewrite your array every time. At the first step you write first line in the array, then you put second line in the array and so on. So at the end you put the last line in your array. Operator >> isn't concatenate all your lines, it's just rewrite it. You can declare vector and then you can write somethink like std:: > allLines;

fileToRead.open("test.txt");
............
std::string temp;
fileToRead >> temp;
allLines.push_back(tmp);
Sergey Kolesov
  • 480
  • 4
  • 15