My program is used for displaying numbers from a .DAT file. There are 2 fields in each line. For example: content of .dat file:
1 2.2
3 10.9
10 100
There are 4 lines in the .DAT file. In the first line, field1 is "1" while field2 is "2.2" And so on. Line 3 is a blank line.
My program is used for displaying the numbers in the same format as we see in the .DAT file which is:
1 2.2
3 10.9
10 100
I do all my programming in Ubuntu. Compiling and running the program in gcc.
My code is shown below:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp = fopen("number.dat", "r");
if (fp == NULL)
{
fprintf(stderr, "ERROR: cannot open the file\n");
return 1;
}
char *field1 = NULL;
char *field2 = NULL;
char line[100];
while(fgets(line, 100, fp)!=NULL)
{
if(line[0] != '\n')
{
field1 = strtok(line, " ");
field2 = strtok(NULL, " ");
printf("%s ", field1);
printf("%s", field2);
}
else
{
printf("Blank Line!");
}
}
fclose(fp);
return 0;
}
However, after i run the program, the result is shown below:
1 2.2
3 10.9
(null)10 100
I do not understand why "(null)" is shown instead of "Blank Line!". Can someone help me find out what the problem is?