Read the text file in char Array. C ++ ifstream

I am trying to read the entire .txt file into a char array. But, having some problems, 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] } 
+6
c ++ arrays char ifstream
source share
4 answers

Each time you read a new line, you overwrite the old one. Save the index variable i and use infile.read(getdata+i,1) , then increase i.

+1
source share

Use std::string :

 std::string contents; contents.assign(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>()); 
+3
source share

You do not need to read line by line if you plan to suck the entire file into the 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... } 
+2
source share
 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); 
+2
source share

All Articles