[問題] Huffman壓縮/解壓

看板C_and_CPP (C/C++)作者 (Sher)時間7年前 (2018/12/27 17:30), 7年前編輯推噓3(303)
留言6則, 5人參與, 7年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Windows 10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) Dev C 之後會移植到Qt上 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 目前針對txt檔案是可以壓縮 與 解壓縮的 只是再對影片檔 圖片檔 等其他檔案無法壓縮 餵入的資料(Input): a.jpg 預期的正確結果(Expected Output): 壓縮後的檔案 STDOUT 會印出編碼表 錯誤結果(Wrong Output): STDOUT 印出空白 或是一兩行亂碼就沒了 也無法進行解壓縮 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) https://ideone.com/ZD7z1f 讀檔部分是 map<char, int> freqs; // frequency for each char from input text int i; // Opening input file // ifstream inputFile; inputFile.open(inputFilepath,std::ifstream::binary | std::ifstream::in ); if (!inputFile) { cerr<<"error: unable to open input file: " << inputFilepath <<endl ; } char ch[1]; //char unsigned total = 0; while (true) { inputFile.read((char*)ch,sizeof(ch)); if(inputFile.eof()) break; //計算頻率 freqs[ch[0]]++; total++; } 感覺是這部分問題 補充說明(Supplement): 有將檔案讀寫部分改成用 c的 fopen(...,rb) 然後fread fwrite等等 可是依然只對txt檔案有用 卡了很久感覺是開檔讀檔的問題 可是又不知道哪裡有問題 故來求解 謝謝各位 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 110.28.37.192 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1545903043.A.D37.html

12/27 17:40, 7年前 , 1F
char 如果是負值怎麼辦
12/27 17:40, 1F
我有想過用unsigned char可是在freqs[ch]++部分會爆掉 ※ 編輯: achicn3 (110.28.37.192), 12/27/2018 17:44:46 剛剛利用 if(ch[0]<0) ch[0] = ~ch[0] 倒是可以壓縮了 只是解壓縮就解不出來了 ※ 編輯: achicn3 (110.28.37.192), 12/27/2018 18:21:37

12/27 19:19, 7年前 , 2F
用unsigned freqs的型態也要改 直接取負號當然無法還原
12/27 19:19, 2F
了解 剛剛發現發現會爆掉是下面的iterator沒改型態 改了之後是可以運作沒錯 可是現在就算用unsigned char去讀 非txt文檔還是無法正常壓縮 會像文章內說的錯誤結 果一樣 ※ 編輯: achicn3 (110.28.37.192), 12/27/2018 20:42:40

12/27 21:24, 7年前 , 3F
先找二進位編輯器生小檔案測試觀察看看?
12/27 21:24, 3F
Ok 還沒嘗試過 ※ 編輯: achicn3 (110.28.37.192), 12/27/2018 23:51:07 我發現問題是在 我建立的新節點字元預設是空白 再根據是不是空白去選擇位置 可是問題是檔案本身可能包含空白字元 這樣子該怎麼處理阿 利用字串嗎? ※ 編輯: achicn3 (110.28.37.192), 12/28/2018 14:31:43

12/28 19:15, 7年前 , 4F
統一用 read/write
12/28 19:15, 4F

12/28 20:31, 7年前 , 5F
空白的問題聽起來跟跳脫字元的故事很像
12/28 20:31, 5F

12/28 21:44, 7年前 , 6F
你會不會table有存錯之類的?
12/28 21:44, 6F
解決了...我將節點字元預設成\0就可以了 感謝各位的回覆 另外特別感謝版友 samuelcdf針對我的code改進寄站內信給我 ※ 編輯: achicn3 (110.28.37.192), 12/28/2018 22:20:45
文章代碼(AID): #1S99l3qt (C_and_CPP)
文章代碼(AID): #1S99l3qt (C_and_CPP)