[問題] 每秒檢查檔案

作者: jacky1989   2016-12-02 21:57:24
開發平台(Platform)(Ex: Win10, Linux, ...) 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
問題(Question):
我設計一個程式每秒去檢查某檔案是否存在
每10秒顯示目前經過秒數
預期的正確結果(Expected Output):
每秒顯示一次資訊
錯誤結果(Wrong Output):
10秒才一次性顯示全部資訊
程式碼(Code):(請善用置底文網頁, 記得排版)
int main(){
FILE *fid_rd;
int count=0,accu=0;
while(1){
fid_rd=fopen(".running","r");
sleep(1);
if(!fid_rd){
printf("finish\n");
break;
}else{
printf(".");
if(count==9){
count=0;
accu+=10;
printf("Simulator has took %d secs\n",accu);
}else
count++;
fclose(fid_rd);
}
return 0;
}
作者: james732 (好人超)   2016-12-02 22:24:00
你需要的可能是fflush (亂猜)
作者: stupid0319 (徵女友)   2016-12-02 22:38:00
sleep(1)?sleep(999)還差不多
作者: Schottky (順風相送)   2016-12-02 22:57:00
printf("."); 後面加 fflush(stdin);printf("."); 後面加 fflush(stdin);還有你為什麼要先 sleep 再檢查 fopen 是否成功...
作者: shadow0326 (非議)   2016-12-02 23:07:00
沒有newline就要自己flush
作者: pttworld (批踢踢世界)   2016-12-02 23:30:00
睡眠時間太短機器可能跟不上,這開檔。int..
作者: MOONY135 (談無慾)   2016-12-02 23:38:00
1是一毫秒喔 至少要800毫秒以上
作者: james732 (好人超)   2016-12-03 00:13:00
https://linux.die.net/man/3/sleep sleep應該是這個?https://goo.gl/CX1x2j 跟這個不一樣
作者: pttworld (批踢踢世界)   2016-12-03 00:22:00
關鍵字:gcc file exists
作者: LPH66 (-6.2598534e+18f)   2016-12-03 00:43:00
什麼 fflush(stdin)... 不要亂教
作者: Schottky (順風相送)   2016-12-03 00:44:00
對不起... 打錯字...
作者: LPH66 (-6.2598534e+18f)   2016-12-03 00:44:00
這裡要 fflush 也是 fflush(stdout), 這個是可以用的
作者: x000032001 (版廢了該走了)   2016-12-03 15:29:00
因為stdout是line buffered

Links booklink

Contact Us: admin [ a t ] ucptt.com