tellg reporting larger file size

I have this function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void LoadASCIIArt(string Location)
{
	char* buffer = 0;
	int FileLength = 0;

	//creating a ifstream object
	ifstream File;

	//opening the file
	File.open(Location.c_str());

	//moving the file pointer to the end of the file, read the length as a streampos, and move the pointer back
	File.seekg(0, ios::end);
	FileLength = (int)File.tellg();
	File.seekg(0, ios::beg);

	//allocate memory
	buffer = new char[FileLength];

	//read the contents into the buffer
	File.read(buffer, FileLength);
	File.close();
	//write the block of data into the output stream.
	cout.write(buffer, FileLength);
	cout.clear();

	delete[] buffer;
};


The problem is that the length returned is much larger then the actual needed space, resulting is garbage data at the end of the string.

I'm not sure what i am doing wrong here, as tellg() is supposed to report the position of the file pointer, which is coincidentally the length of the file.

tellg() is supposed to report the position of the file pointer, which is coincidentally the length of the file.

That is only true for the files opened in binary mode. For text mode, which you're using, C++ (and C, for that matter) file pointer is not necessarily related to file size. Try opening the file with ios::binary.
Last edited on
Thanks.. I didn't realize that i could open a text file in binary mode.
Topic archived. No new replies allowed.