I want to read a file, the first two lines. the program is :
int main(void)
{
FILE *fp;
char buf[1024];
char value[128];
long mem[2];
char *pos;
if (!(fp = fopen("example.txt", "r"))) {
printf("CANNOT open example.txt\n");
return -2;
}
for(int i = 0; i < 2; ++i) {
fgets(buf, 1024, fp);
pos = strstr(buf, ":");
if (!pos) {
printf("MEMINFO wrong format\n");
return -1;
}
strncpy(value, pos + 1, 128);
mem[i] = atol(value);
memset(buf, 0, sizeof(buf));
memset(value, 0, sizeof(buf));
}
}
and example.txt is like :
MemTotal: 3541412 kB
MemFree: 123500 kB
Buffers: 11372 kB
Cached: 2582072 kB
SwapCached: 1520 kB
Active: 1832328 kB
Inactive: 1493348 kB
Active(anon): 1608692 kB
Inactive(anon): 1269620 kB
Active(file): 223636 kB
It generates a segfault error when the second fgets is reached. Using gdb, I found the file pointer fp becomes 0 in the second fgets. What is the problem? Can fgets be used like this?
You need to check that
fgets()succeeds, before relying on the results.Also, why are you doing the
memset()calls, bothbufandvalueshould be overwritten when all goes well anyway. It causes a bug:Wrong buffer size.