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