這裏是我的代碼,以獲取有關網絡設備的系統信息:爲什麼我需要重新打開文件才能獲得最新的數據?
FILE* f = fopen(filePath, "r");
if(f == NULL)
{
perror("Error while open the file:");
return -1;
}
while(1)
{
fseek(f, 0, SEEK_SET);
char s[20];
fgets(s, 20, f);
int len = strlen(s);
s[len] = '\0';
printf(" %20s\r", s);
fflush(stdout);
sleep(2);
}
但輸出的只是保持不變,比我決定每次我需要閱讀它的時間來重新打開文件 :
while(1)
{
FILE* f = fopen(filePath, "r");
if(f == NULL)
{
perror("Error while open the file:");
return -1;
}
char s[20];
fgets(s, 20, f);
int len = strlen(s);
s[len] = '\0';
char output[50];
printf(" %20s\r", s);
fflush(stdout);
sleep(2);
}
and everything worked just fine, but I don't know why?
你應該關閉你打開的任何東西。 – MikeCAT
謝謝。但我的觀點是,是否可以每次打開一個文件並從頭讀取以獲取其最新數據?從我粘貼的第一個代碼示例看來,即使文件已更新,數據仍然保持不變。 – hustxujinkang
你正在閱讀什麼文件?它是基於磁盤的文件還是僞文件系統中的某個文件? – subin