[問題] 請問fopen後,檔案被別人更動時,如何씠…

看板C_and_CPP作者 (annie)時間13年前 (2011/05/11 22:57), 編輯推噓1(1011)
留言12則, 5人參與, 最新討論串1/1
開發平台(Platform): Linux 額外使用到的函數庫(Library Used): non 問題(Question): 各位前輩好, 我現在需要透過檔案做狀態的輪詢,檔名叫msg,固定只存32bit的值。 我的程式用fopen打開msg後,每隔一段時間用fscanf去讀msg的值, 同時間會有另一個程式不定時更新msg的內容, 如果用vim去看msg,值都有更新 但是我的程式一值只讀到最初的值, 請問該怎麼樣才能抓到更新後的內容呢? ps.因為輪詢的頻率很高,所以不能在每次讀值前才fopen, 避免頻繁的開關檔案。 謝謝各位前輩! #include "stdio.h" int main() { FILE *p1; FILE *p2; int i,s1,s2; p1 = fopen("msg","r"); for (i=0;i<50;i++) { // the context of msg will be changed at random time sleep(3); // just for test, let test time longer fscanf(p1,"%d",&s1); printf("%d\n",s1); // always the old value p2=fope("msg","r"); fscanf(p2,"%d",&s2); printf("%d\n",s2); // will be the newest value fclose(p2); } fclose(p1); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.66.243.96 ※ 編輯: anniebu 來自: 61.66.243.96 (05/11 23:05)

05/11 23:57, , 1F
google "IPC"
05/11 23:57, 1F

05/12 00:32, , 2F
你就不要頻繁的fopen阿...
05/12 00:32, 2F

05/12 00:57, , 3F
用stat()來抓檔案的修改時間 發現被改了再開檔讀它
05/12 00:57, 3F

05/12 00:58, , 4F
答非所問了XD 不知道這樣能不能符合你的需求
05/12 00:58, 4F

05/12 01:06, , 5F
你的fopen每次都是從開頭讀 當然是初始值阿
05/12 01:06, 5F

05/12 01:16, , 6F
突然發現 原PO的p1除了第一次fscanf 之後根本沒讀到東西嘛
05/12 01:16, 6F

05/12 09:07, , 7F
我想這支程式只是例子,我剛剛才懂你的問題,因為你p2打開
05/12 09:07, 7F

05/12 09:08, , 8F
隨即後又關閉,當然永遠只讀到第一個數字的內容.
05/12 09:08, 8F

05/12 09:09, , 9F
兩種做法,第一種,記錄你目前讀到哪,然後用fseek去移動
05/12 09:09, 9F

05/12 09:11, , 10F
第二種,p2=fopen和fclose(p2)請移到for迴圈之外.
05/12 09:11, 10F

05/12 12:09, , 11F
利用fgetpos 和 gsetpos 就可以處理了 :p
05/12 12:09, 11F

05/12 16:05, , 12F
fsetpos才對.
05/12 16:05, 12F
文章代碼(AID): #1DogFp8o (C_and_CPP)