转换为二进制文件

时间:2017-11-24 04:59:13

标签: c file binaryfiles

我需要将以下格式的文本文件转换为二进制文件。 输入文件仅包含字符A,B,C或D.' A'更改为''' B'更改为' 01',C更改为' 10',D更改为' 11'。 示例输入文件:

ABBCDA
BBAABCD
BACBB

示例输出文件:

000101101100
01010000011011
0100100101

我已经编写了以下代码,但它无法正常工作。

int main()
{
    FILE * fop;
    FILE * fout;
    int length=0;
    int i;
    char buffer[1000];
    fop = fopen("filename.txt","r");
    fout = fopen("filename.bin", "wb");
    while(!feof(fop))
    {
        fgets(buffer,1000,fop);
        length = strlen(buffer)-1;
        for(i=0; i<length; i++)
         {
           if(buffer[i]=='A')
           strcpy(buffer[i],'00');
           if(buffer[i]=='B')
           strcpy(buffer[i],'01');
           if(buffer[i]=='C')
           strcpy(buffer[i],'10');
           if(buffer[i]=='D')
           strcpy(buffer[i],'11'); 
         }
      fwrite(buffer, 1, sizeof(char)*length, fout);
      fwrite("\n",1,sizeof(char),fout);
    }
    fclose(fop);
    fclose(fout);
    return 0;
}

出了什么问题?怎么解决?谢谢。

1 个答案:

答案 0 :(得分:2)

这是要修复的部分

while(fgets(buffer,1000,fop))
{
    length = strlen(buffer)-1;
    char sout[3];
    for(i=0; i<length; i++)
    {
        *sout = '\0';
        if(buffer[i]=='A')
            strcpy(sout,"00");
        if(buffer[i]=='B')
            strcpy(sout,"01");
        if(buffer[i]=='C')
            strcpy(sout,"10");
        if(buffer[i]=='D')
            strcpy(sout,"11"); 
        fwrite(sout, 1, strlen(sout), fout);
    }
    fwrite("\n",1,sizeof(char),fout);
}

注释

  • fgets条件中的while
  • sout暂时存储2位(字符串)
  • fwrite写入sout(不覆盖缓冲区),并且在\n的写入位于外部时集成在for循环中。

写入实际字节的版本(二进制)......

while(fgets(buffer,1000,fop))
{
    length = strlen(buffer)-1;
    for(i=0; i<length; i++)
    {
        unsigned char byte = 0;
        if(buffer[i]=='A')
            byte = 0x0;
        if(buffer[i]=='B')
            byte = 0x1;
        if(buffer[i]=='C')
            byte = 0x2;
        if(buffer[i]=='D')
            byte = 0x3; 
        fwrite(&byte, 1, 1, fout);
    }
    // no more : fwrite("\n",1,sizeof(char),fout);
}

使用0x符号表示我正在处理二进制内容......

版本David C. Rankin(完美主义者!)

while (fgets (buf, MAXC, fop)) {    /* read each line */
    char *p = buf;                  /* pointer to buf */
    while (*p) {                    /* while not '\0' */
        uint8_t byte = 0;           /* declare byte */
        if ('A' <= *p && *p <= 'Z') /* if char is A-Z */
            byte = *p - 'A';        /* encode 0 - 25 */
        else
            byte = *p;              /* write char as is */
        if (fwrite (&byte, 1, 1, fout) != 1) {   /* validate write */
            fprintf (stderr, "error: write of '%c' failed.\n", *p);
            goto badwrite;          /* jump out of loops on fail */
        }
        p++;    /* increment pointer */
    }
}
badwrite:;

fclose (fop);                /* close input file */
if (fclose (fout) == -1)     /* close/validate output file */
    fprintf (stderr, "error: on fout close.\n");

还有一些东西可以改进,但现在......