1. 程式人生 > >C語言 讀寫二進制文件

C語言 讀寫二進制文件

c 統計 字符串 二進制文件


查找了比較多的資源, 發現沒有辦法把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


本文出自 “R和Python應用” 博客,請務必保留此出處http://matrix6ro.blog.51cto.com/1746429/1943718

C語言 讀寫二進制文件