看板 C_and_CPP 關於我們 聯絡資訊
編譯器(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; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.214.129.158 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1480687047.A.6FF.html
james732: 你需要的可能是fflush (亂猜)12/02 22:24
stupid0319: sleep(1)?12/02 22:38
stupid0319: sleep(999)還差不多12/02 22:39
Schottky: printf("."); 後面加 fflush(stdin);12/02 22:57
Schottky: printf("."); 後面加 fflush(stdin);12/02 22:57
Schottky: 還有你為什麼要先 sleep 再檢查 fopen 是否成功...12/02 22:58
shadow0326: 沒有newline就要自己flush12/02 23:07
※ 編輯: jacky1989 (49.214.130.241), 12/02/2016 23:13:26
pttworld: 睡眠時間太短機器可能跟不上,這開檔。int.. 12/02 23:30
MOONY135: 1是一毫秒喔 至少要800毫秒以上 12/02 23:38
james732: https://linux.die.net/man/3/sleep sleep應該是這個? 12/03 00:13
james732: https://goo.gl/CX1x2j 跟這個不一樣 12/03 00:14
pttworld: 關鍵字:gcc file exists 12/03 00:22
LPH66: 什麼 fflush(stdin)... 不要亂教 12/03 00:43
Schottky: 對不起... 打錯字... 12/03 00:44
LPH66: 這裡要 fflush 也是 fflush(stdout), 這個是可以用的 12/03 00:44
想請問為什麼需要fflush呢? ※ 編輯: jacky1989 (123.192.57.91), 12/03/2016 02:50:12 ※ 編輯: jacky1989 (123.192.57.91), 12/03/2016 02:52:03
LPH66: 基本上是在猜測 printf 出來的東西因為被 buffer 住了 12/03 08:25
LPH66: 所以在推出去到螢幕之前就 sleep 了導致東西一次印出來 12/03 08:27
LPH66: fflush(stdout); 就是在強迫這些 buffer 住的東西印出來 12/03 08:27
x000032001: 因為stdout是line buffered 12/03 15:29