这里是我的代码,以获取有关网络设备的系统信息:为什么我需要重新打开文件才能获得最新的数据?
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