Reputation: 101
I have a file that exists in the same directory as my .c and my executable under Linux. 99 times out of 100 it will open the file correctly and not return a null pointer. But this 1 time out of 100 it will return a null pointer, the code is shown below. Why would I only sometimes get a null pointer for this file? And why when I do get the null pointer does it fail to create a file with the same name if Linux thinks it doesn't exist?
int ID_Lookup(int serialNumber, int NodeID)
{
FILE *nodeidfile = NULL;
char temp[8];
char *filebuff;
int commapos, endpos;
int fileserialnum = 0, id = 9, match = 0, x = 0, linechar = 0, y;
size_t len = 0;
nodeidfile = fopen("NodeIDs","r");
if (nodeidfile == NULL)
{
printf("file not found, creating it\r\n");
nodeidfile = fopen("NodeIDs","w");
fclose(nodeidfile);
}
nodeidfile = fopen("NodeIDs","r");
if (nodeidfile == NULL)
return -1;
printf("file found\r\n");
fseek(nodeidfile,0,SEEK_END);
len = ftell(nodeidfile);
fclose(nodeidfile);
return 0;
}
Upvotes: 0
Views: 376
Reputation: 4382
If fopen succeeds the first time, you open the file again (abandoning the first FILE* -- you're no longer able to close that first file). This system eventually runs out of file handles.
You should handle the two cases independently.
int ID_Lookup(int serialNumber, int NodeID)
{
FILE *nodeidfile = NULL;
char temp[8];
char *filebuff;
int commapos, endpos;
int fileserialnum = 0, id = 9, match = 0, x = 0, linechar = 0, y;
size_t len = 0;
nodeidfile = fopen("NodeIDs","r");
if (nodeidfile == NULL)
{
printf("file not found, creating it\r\n");
nodeidfile = fopen("NodeIDs","w");
fclose(nodeidfile);
return 0;
}
printf("file found\r\n");
fseek(nodeidfile,0,SEEK_END);
len = ftell(nodeidfile);
fclose(nodeidfile);
return 0; /* should return len? */
}
Upvotes: 3