[問題] 如何有效讀檔

看板C_and_CPP作者 (梅)時間13年前 (2011/04/27 18:42), 編輯推噓0(0011)
留言11則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) stdio.h 問題(Question): 我想要讀system("top")的特定內容 我的想法是想先執行system("top c>top_info.txt"); 然後再利用FILE *fp = fopen("top_info.txt","r"); 下面是利用指令"top c"得到的內容: last pid: 98368; load averages: 0.00, 0.00, 0.00 up 29+23:54:36 17:35:10 88 processes: 4 running, 64 sleeping, 20 waiting CPU states: 0.0% user, 0.0% nice, 0.0% system, 0.0% interrupt, 0.0% idle Mem: 25M Active, 1698M Inact, 195M Wired, 77M Cache, 112M Buf, 7452K Free Swap: 4096M Total, 4096M Free 可是在這些資料中,我只想要得到load averages, CPU states, Mem和Cache的資料, 其他我都不需要。 想要請問要如何寫讀檔,才可以有效率的讀到我想要的這幾個值呢? 請幫幫忙我解惑 感激不盡>_<" -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 163.25.118.153

04/27 18:46, , 1F
fscanf
04/27 18:46, 1F

04/27 18:48, , 2F
請問要怎麼使用fscanf來達到這樣的需求?
04/27 18:48, 2F

04/27 18:51, , 3F
因為我現在正在嘗試fscanf。難道要命一堆變數,依序存嗎?
04/27 18:51, 3F

04/27 19:17, , 4F
不需要的地方可以用 * 跳過不存
04/27 19:17, 4F

04/27 19:17, , 5F
像scanf("last pid: %*d; load averages: %lf, %lf, %lf"
04/27 19:17, 5F

04/27 19:17, , 6F
我是比較喜歡用 fgets(input, 100, file);
04/27 19:17, 6F

04/27 19:17, , 7F
temp = strstr(input, "load averages:");
04/27 19:17, 7F

04/27 19:17, , 8F
sscanf(temp, "load averages: %lf, %lf, %lf" 這樣做
04/27 19:17, 8F

04/27 23:34, , 9F
你可以用grep來過濾你想要的啊...
04/27 23:34, 9F

04/29 16:58, , 10F
我比較好奇top是隨時更動的,你要下什麼條件讓他停止
04/29 16:58, 10F

05/04 01:54, , 11F
我是定期的去檢視機器的使用狀態,所以應該不用停止啦
05/04 01:54, 11F
文章代碼(AID): #1Dj_CJdz (C_and_CPP)