How to Open Large Files in C
I was using some code like this to open a 2.4GB file in my 32 bit Ubuntu installation:
#include <stdio.h>
#include <string.h>
int main ()
{
FILE * pFile;
pFile = fopen ("unexist.ent","r");
if (pFile == NULL)
printf ("Error opening file unexist.ent\\n";
return 0;
}
But I kept getting a null pointer back.
The first step I did was try to get a more detailed error message. It turns out there’s an errno standard lib that gives you error messages about files. I implemented the changes recommended by this page:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main ()
{
FILE * pFile;
pFile = fopen ("unexist.ent","r");
if (pFile == NULL)
printf ("Error opening file unexist.ent: %s\\n",strerror(errno));
return 0;
}
And I got this message:
Value too large for defined data type
So thanks to advice from the C irc chat room, I switched to using fopen64, and everything worked!
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main ()
{
FILE * pFile;
pFile =fopen64("unexist.ent","r");
if (pFile == NULL)
printf ("Error opening file unexist.ent: %s\\n",strerror(errno));
return 0;
}