查找了比較多的資源, 發現沒有辦法把text 文件轉成binary文件ide
僅做爲記錄,不過這個例子能夠去除換行符。.net
#include <stdio.h> #include <string.h> #define N 255 int main() { char a[N]; FILE *fp1,*fp2; fp1=fopen("test_seq.fa","r"); fp2=fopen("testSeq.dat","wb"); /* input text file and output ASCII file no line delimiter*/ if (NULL == fp1){ return -1; } while(!feof(fp1)){ if(feof(fp1)){ break; } fscanf(fp1,"%s", a); //fwrite(a, strlen(a),1,fp2); fwrite(&a, sizeof(char), strlen(a) ,fp2); } fclose(fp1); fclose(fp2); return 0; }
編譯後, 程序讀入test _ seq. fablog
輸出是 testSeq. dat資源
#include <stdio.h> #include <string.h> int main(void){ int len=2048; char filename[20]; char buff[10000]; char hit[5]; // str for find FILE *fd; int i,j,flag=0,over=0; int max,readed; int count=0; //strcpy(&filename[0] , "test_seq.fa"); // file name strcpy(&filename[0] , "testSeq.dat"); // file name strcpy(&hit[0] , "agag"); // sequence buff[0]=0x0; buff[1]=0x0; // open file if((fd = fopen(&filename[0] , "rb"))==NULL){ printf("Error : Can not open file %s\n",&filename[0]); } // read content while(over != 1){ readed = fread(&buff[2] , 1 , len , fd); if(readed < len){ over=1; max=readed; }else{ max=len; } for(i=0;i<max;i++){ for(j=0;j<4;j++){ if(hit[j] != buff[i+j]){ flag=0;// break; }else{ flag=1;// } } if(flag==1){ count++; i+=j-1; }else{ if(j==0){ i+=(j); }else{ i+=(j-1); } } } // buff[0]=buff[max]; buff[1]=buff[max+1]; } fclose(fd); printf("count:%d\n",count); }
這個程序編譯後 ,讀入testSeq.dat , 統計其中的 agag 字符串的個數。字符串
二進制文件讀取 參考get
https://stackoverflow.com/questions/15752546/binary-file-reading-writing-in-c input
https://stackoverflow.com/questions/33252160/how-to-read-from-binary-file-to-a-text-file-in-c string
https://www.codingunit.com/c-tutorial-binary-file-io it