I've been having trouble reading text files for some time now. So now I've got a few questions:
I use this code to load a textfile to RAM:
CODE
cout << "Reading file to RAM..." << endl;
inputFile.seekg(0, ios::end);
unsigned int fileLength = inputFile.tellg();
inputFile.seekg(0, ios::beg);
char *fileData = (char*) malloc(fileLength);
if (fileData == NULL) {
cerr << "Not enough memory availble..." << endl
<< "Press ENTER to exit...";
cin.get();
return 0;
}
inputFile.read(fileData, fileLength);
inputFile.close();
I find get the length of the file by setting the file pointer to the end, and then read at what position it is. This will return the number of characters in the file. Then I allocate that size to the char* fileData and save the contents of the file to that piece of RAM.
The only trouble I'm having is that the length of fileData as a string is different than fileLength (the number of characters in the file). The rest of the array is filled with zero's.
Why is this? Isn't each character in the file copied into the array?
And what's the deal with newlines? Windows saves a newline as CR NL, Unix as NL and MacOS as CR. How is handled by C++?