As an exercise, I am creating a "Database" that stores data from a structure array in a .txt file.
When reading the data from the file I used strtok
to assign each value to the corresponding structure member since they were separated with whitespace and they are formatted in this specific way.
#value0 #value1 #value2 #value3
randomstring randomstring randomstring random_4digit_long
randomstring randomstring randomstring random_4digit_long
This works great until strtok
returns the NULL
value since it reaches the end of string.The structure here is named items
and is of type myStruct
long loadData(myStruct *items, long len, char *inputFile){
FILE *openedFile;
openedFile= fopen(inputFile,"r");
if (openedFile==NULL)
{
fprintf(stderr,"No file found.\n");
fclose(openedFile);
return -1;
}
else
{
fscanf(openedFile, "%*[^\n]"); //Discard first line
getc(openedFile); //get remaining \n character
char * token;
char line[80];
char * pointer=line;
for (int i=0; i<=len;i++)
{
if(NULL==fgets(pointer,80,openedFile)) //get each line and check if empty
{
break;
}
token = strtok(pointer, " ");
if (strcmp(token,"\n")==0 || !token) //Comparison Point
{
fprintf(stderr,"File has wrong format.\n");
fclose(openedFile);
return -1;
}
strcpy(items[i].value0,token);
for(int j=0;j<=2;j++)
{
token = strtok(NULL," ");
if (strcmp(token,"\n")==0 || !token) //Comparison Point
{
fprintf(stderr,"File has wrong format.\n");
fclose(openedFile);
return -1;
}
if(j==0)
{
strcpy(items[i].value1,token);
}
else if(j==1)
{
strcpy(items[i].value2,token);
}
else if(j==2)
{
items[i].value3=atoi(token);
}
}
}
fclose(openedFile);
return 0;
}
When the .txt file is formatted as intended it works perfectly. When The format is not, I've got the comparison point to check for anomalies. When the .txt file has for example two values that are empty then strtok
returns NULL
because it has reached the end of the string prematurely. Then when the comparison takes place, it creates a segmentation fault. I've tried many ways that I found on google about NULL
checking a pointer but none seems to work. I need to make this comparison in order for the condition of the formatting to hold.
From what I've read, when the comparison takes place and the token
pointer is NULL
then the !token
condition would be ok, but here it doesn't work, any ideas why?