查找了比较多的资源, 发现没有办法把text 文件转成binary文件
仅作为记录,不过这个例子可以去除换行符。
#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. fa
输出是 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 字符串的个数。
二进制文件读取 参考
https://stackoverflow.com/questions/15752546/binary-file-reading-writing-in-c
https://stackoverflow.com/questions/33252160/how-to-read-from-binary-file-to-a-text-file-in-c
https://www.codingunit.com/c-tutorial-binary-file-io
http://blog.csdn.net/bly1126/article/details/6020728
https://my.oschina.net/chuqixiaozhu/blog/386384
转载于:https://blog.51cto.com/matrix6ro/1943718