[問題] 連續讀檔(fopen)無法fclose

看板C_and_CPP (C/C++)作者 (JIM)時間11年前 (2015/03/26 18:14), 11年前編輯推噓3(3011)
留言14則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) OpenCV 問題(Question): 我想要做出判斷一個資料夾裡面有多少張ABC%d.bmp的圖 然後再拿最後一張圖來做辨識 因此我想到的方法是用while配合fopen來rb找到最後一張 再用opencv來imread 但是目前情況是 1.辨識到第43張圖時就會發生test和train檔案大小不符 (應該是開到ABC%d+1.bmp空檔去了) 2.只要我在程式後面加上fclose,進行辨識時就會發生 Caught SIGSEGV accessing address (nil) Spinning. Please run 'gdb gst-launch 1321' to continue debugging, Ctrl-C to quit, or Ctrl-\ to dump core. 困擾蠻久的,一直沒辦法找到好的方法解決, 麻煩大家幫忙看看了!謝謝! 程式碼(SourceCode): int count = 0; char iconpath[200]; FILE *fp; sprintf(iconpath,"/var/ABC%d.bmp",count); fp=fopen(iconpath,"rb"); while(fp){ count++; sprintf(iconpath,"/var/ABC%d.bmp",count); fp=fopen(iconpath,"rb"); } sprintf(iconpath,"/var/ABC%d.bmp",count-1); Mat img = imread(iconpath, CV_LOAD_IMAGE_GRAYSCALE); memset(iconpath,0x00,200); int predicted_label = -1; double predicted_confidence = 0.0; model->predict(img, predicted_label, predicted_confidence); *label=predicted_label; *conf=predicted_confidence; fclose(fp); -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.123.112.60 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1427364898.A.F67.html

03/26 18:42, , 1F
while() 裡面新開一個檔時先把舊的關掉
03/26 18:42, 1F

03/26 18:42, , 2F
另外你思考一下 while 出去的時候 fp 到底是什麼東西
03/26 18:42, 2F

03/26 18:43, , 3F
這直接關係到你最後的 segfault
03/26 18:43, 3F

03/26 18:45, , 4F
再來, 要檢查檔案是否存在其實不只有開開看一個方法
03/26 18:45, 4F
我之前是把迴圈擺在while第一句跟程式結束前 確實沒想到您說的while出去時的fp 非常謝謝您提供寶貴的建議 已經可以work了 等到有時間再來找找有沒有其他複雜度低一點的檢查方法了 謝謝指導~~

03/27 19:52, , 5F
不考慮用 ls 列出檔案?
03/27 19:52, 5F
不曉得怎麼讓linux bash的指令結果讓我的程式讀取耶 請問n大有什麼關鍵字可以提供我去尋求答案嗎~~ 感覺要判別資料夾數量 fopen就不可行了..

03/29 17:03, , 6F
python可以直接用os.system()叫出系統指令並執行
03/29 17:03, 6F

03/29 17:04, , 7F
c好像有python的lib可以用,可以試試喔
03/29 17:04, 7F

03/29 18:01, , 8F
linux上opendir這裡有個簡例: http://ppt.cc/vumE
03/29 18:01, 8F

03/29 18:06, , 9F
讀shell結果我這裡有個簡例: http://codepad.org/GlW5bmNm
03/29 18:06, 9F

03/29 18:14, , 10F
exec("find . -maxdepth 1 -type f -iname \'*.bmp\'
03/29 18:14, 10F

03/29 18:15, , 11F
-printf \'%f\\n\'") 兩行貼起來
03/29 18:15, 11F

03/29 18:16, , 12F
不用std::string的話自己調整囉
03/29 18:16, 12F

03/31 00:55, , 13F
你while(fp) 所以當然跳出迴圈的時候fp是nil啊
03/31 00:55, 13F

03/31 00:57, , 14F
可以用opendir, readdir跟access
03/31 00:57, 14F
非常謝謝各位的解答,問題已經解決了! ※ 編輯: jiqian (140.123.112.60), 04/15/2015 15:06:28
文章代碼(AID): #1L4zmYzd (C_and_CPP)
文章代碼(AID): #1L4zmYzd (C_and_CPP)