Read text file into char Array. C++ ifstream

39,926

Solution 1

Every time you read a new line you overwrite the old one. Keep an index variable i and use infile.read(getdata+i,1) then increment i.

Solution 2

std::ifstream infile;
infile.open("Textfile.txt", std::ios::binary);
infile.seekg(0, std::ios::end);
size_t file_size_in_byte = infile.tellg();
std::vector<char> data; // used to store text data
data.resize(file_size_in_byte);
infile.seekg(0, std::ios::beg);
infile.read(&data[0], file_size_in_byte);

Solution 3

Use std::string:

std::string contents;

contents.assign(std::istreambuf_iterator<char>(infile),
                std::istreambuf_iterator<char>());

Solution 4

You don't need to read line by line if you're planning to suck the entire file into a buffer.

char getdata[10000];
infile.read(getdata, sizeof getdata);
if (infile.eof())
{
    // got the whole file...
    size_t bytes_really_read = infile.gcount();

}
else if (infile.fail())
{
    // some other error...
}
else
{
    // getdata must be full, but the file is larger...

}
Share:
39,926
nubme
Author by

nubme

Updated on March 14, 2020

Comments

  • nubme
    nubme about 4 years

    Im trying to read the whole file.txt into a char array. But having some issues, suggestions please =]

    ifstream infile;
    infile.open("file.txt");
    
    char getdata[10000]
    while (!infile.eof()){
      infile.getline(getdata,sizeof(infile));
      // if i cout here it looks fine
      //cout << getdata << endl;
    }
    
     //but this outputs the last half of the file + trash
     for (int i=0; i<10000; i++){
       cout << getdata[i]
     }
    
  • Tony Delroy
    Tony Delroy over 13 years
    read(..., 1) reads one character at a time... very inefficient.
  • tmiddlet
    tmiddlet over 13 years
    infile.seekg(0,ios::end);int len = infile.peekg();infile.seekg(0,ios::beg);infile.read(getdata,‌​len);
  • Nawaz
    Nawaz about 10 years
    What if the file is bigger than 10000 chars?
  • Nawaz
    Nawaz about 10 years
    .... and what you're going to do there? declare another char array of bigger size and read again? wrong, isn't it?
  • gluk47
    gluk47 over 8 years
    ...always had troubles memorizing this spell. Not quite intuitive. PS. Since OP requested a char array, contents.c_str() can be of use.