Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text file into char Array. C++ ifstream

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]
 }
like image 679
nubme Avatar asked Dec 07 '10 03:12

nubme


People also ask

How do I convert a text file to an array in C++?

Insert data from text file into an array in C++ Firstly we start from header file in which we used three header file(iostream,fstream,string) iostream is used for input output stream and fstream is used for both input and output operations and use to create files, string is used for Saving The Line Into The Array.

How do you read a line of characters in C++?

The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.


1 Answers

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);
like image 58
Vertexwahn Avatar answered Nov 10 '22 10:11

Vertexwahn