linux下讀取windows檔案遇到的問題

來源:互聯網
上載者:User




  1 #include <stdio.h>  2 #include <string.h>  3 int main(int argc, char *argv[])  4 {  5     char buf[1024];  6     FILE *fp ;  7     FILE *dst_fp;  8     int i,j;  9     char *line; 10     char file_name[256]; 11     int space_line = 2; 12     int skip_line = 3; 13  14     for(i = 0; i < argc; i++) { 15  16         if(strcmp(argv[i],"-i") == 0){ 17             strcpy(file_name,argv[i+1]); 18             break; 19         } 20     } 21      22     if((fp = fopen(file_name,"rb"))==NULL) 23         printf("Open file error!\n"); 24  25     dst_fp = fopen("processed_by_c.txt","wb"); 26      27     i=0; 28      29     fseek(fp, 0, SEEK_SET); 30      31     while((line = fgets(buf,1024,fp)) != NULL){ 32         fputs(line,dst_fp); 33         i++; 34         if(i == skip_line) {
 35             i=0; 36             j=0; 37             while(j < space_line) { 38                 j++; 39                 fputc('\r',dst_fp); 40                 fputc('\n',dst_fp); 41             } 42         } 43         fflush(dst_fp); 44     } 45     fclose(fp); 46     fclose(dst_fp); 47     return 0; 48  49 }                                                                                                                                             10,1          T

在windows下產生了一個資料檔案a.txt, 準備在linux下進行處理並且產生一個新的檔案。具體處理是將檔案每隔n行空m行。

原始碼如上:

經過測試發現最終產生的檔案為亂碼,找了好久排除了程式的邏輯問題。自己用vim重建了一個txt檔案測試發現沒有問題。於是很自然想到了字元編碼的問題。

通過運行hexdump a.txt發現開頭是0xfeff,而且每個字元前面都是0x00,佔兩個位元組,明顯的unicode編碼,而用vim在linux下產生的確沒有。

於是通過命令iconv -f unicode -t ascii -o a_new.txt a.txt  先將原來的unicode檔案轉化為ascii編碼的檔案。

運行程式,OK


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.