我想讀一個文件,前兩行。該程序是:爲什麼執行第二個fgets時,C中的文件指針變爲空?
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));
}
}
和example.txt中是這樣的:
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
它產生達到第二與fgets時段錯誤錯誤。使用gdb,我發現文件指針fp在第二個fgets中變爲0。問題是什麼? fgets可以像這樣使用嗎?
發佈'example.txt'的內容 – tuxuday
總是檢查fgets的錯誤:: http://msdn.microsoft.com/en-us/library/c37dh6kf(v=vs.71).aspx 你可以使用「strchr」如果搜索一個字符:: http://msdn.microsoft.com/en-us/library/b34ccac3(v=vs.71).aspx – Abhineet