Jump to content
  • Advertisement
Sign in to follow this  

Using fread to Read a Text File

This topic is 2878 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'm trying to read a file very quickly. I My tests have shown that reading line by line with "getline()" is slower than seeking to the end of the file and then reading it all at once with fread. Right now, I'm trying to get fread to work properly.

Test file:
hydrogen, helium
My test code, taken from several sources:
typedef uint8_t using_type;

FILE* pFile = fopen(path,"r");
long lSize = ftell(pFile)/sizeof(using_type);

using_type* buffer = (using_type*)malloc(sizeof(using_type)*lSize);
if (buffer == NULL) {
fputs("Memory error",stderr);
// copy the file into the buffer:
size_t result = fread(buffer,1,lSize,pFile);
if (result != lSize) {
fputs("Reading error",stderr);
fclose (pFile);
free (buffer);
When using "r" mode, the contents of "buffer" seem to be somewhat meaningful:
hydrogen, heliumÍÍýýýý««««««««"
However, the second error trips (because result==50 and lSize==52). When using "rb" mode, result==lSize==52, but the contents of "buffer" are garbage:
0x00d960c8 "îþîþîþîþîþîþîþîþ...[etc.]...îþîþîþîþîþîþîþîþîþ{x"

Help? Thanks,

Share this post

Link to post
Share on other sites
In "r" mode, the difference between result and lSize seems to be the number of newlines in the file. However, removing all newlines results in garbage again!

Share this post

Link to post
Share on other sites
i have similar problem but have solved it with a parser.
The problem is that windows texteditors dont use \n to mark new lines.
They use \n\r to mark newlines.

If im right, the binarymode reads both signs \n\r and the textmode jut reads \n

Share this post

Link to post
Share on other sites
Moving to For Beginners.

You are doing a lot of strange and probably wrong things here, and I can't begin to imagine how you can simultaneously (a) require maximum performance reading from a file and (b) not be able to fix it yourself and have a complete understanding of what is going on.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!