Jump to content
  • Advertisement
Sign in to follow this  

Getting size of file

This topic is 3664 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have this short snippet to figure out the size of a file:
		// get size of file
		FILE* stream = fopen(filename.c_str(), "r");
		fseek(stream, 0L, SEEK_END);
		long size = ftell(stream);

Then, based on the reported size, I allocate a char* buffer to read it:
		// read file contents
		std::ifstream f(filename.c_str());
		if (f.is_open())
			char* buffer = new char[size];
			f.read(buffer, size);

Problem is, "buffer" ends up holding this:
content of file will be printed to coutýýýý««««««««þîþîþ
My question is what those extra 17 characters at the end are. Metadata hold in the .txt? Whats the best way to get rid of them? Doing size-=17; seems like a last resort. [edit] The content of the file looks like this:
content of file will be printed to cout
(no new line)

Share this post

Link to post
Share on other sites
you aren't null terminating your buffer, so it is just printing the random garbage in memory up to the first NULL.

char* buffer = new char[size+1];
f.read(buffer, size);
buffer[size] = NULL;

in reality you prolly want something more like

std::copy( buffer, buffer+size, std::output_iterator<T>( cout ) );

to account for files with NULL's in them.

Share this post

Link to post
Share on other sites
You can determine the file size using the fstream seekg and tellg methods while keeping the file open and avoiding having to resort to c-style FILE routines. This will also save you from any compilications if the file is inadvertently manipuated between the two open calls.

f.open( filename.c_str() /*, std::ios::in | std::ios::binary*/);
f.seekg (0, std::ios::end);
size_t file_sz = f.tellg();
f.seekg (0, std::ios::beg);

char *buf = new char [ file_sz + 1];
f.read( buf, file_sz);
buf[ file_sz] = 0;

Additionally you can get exception safety - ie the newed memory wont leak if an exception is pulled [for instance due to interacting with the c++ standard library] if you read into a data structure rather than raw newed' byte buffer - vectors work pretty well for this.

std::vector< char> buf( file_sz);
f.read( &buf[ 0], buf.size());

the output function to std out would then be,

std::copy( buf.begin(), buf.end(), std::ostream_iterator< char>( std::cout ));

or even just,

std::cout.write( &buf[ 0], buf.size());

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!