Write a file in c of an array of integers with fputc

后端 未结 3 677
鱼传尺愫
鱼传尺愫 2021-01-17 07:52

I\'m writing a program that reads a file and generates an array of integers of each byte, first I prove with a .txt file and I generates the ASCII for each of the letters an

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 08:48

    You should reconstruct the integer starting from your array using your mask array.

    #include
    
    int main(void)
    {
    
        int b1, b2, b3, b4, b5, b6, b7, b8;
        int x, i;
        char a, b;
    
        FILE *f1, *bin, *fp;
    
        b1 = 0x01; // = 0000 0001
        b2 = 0x02; // = 0000 0010
        b3 = 0x04; // = 0000 0100
        b4 = 0x08; // = 0000 1000
        b5 = 0x10; // = 0001 0000
        b6 = 0x20; // = 0010 0000
        b7 = 0x40; // = 0100 0000
        b8 = 0x80; // = 1000 0000
    
        int mask[8] = { b8, b7, b6, b5, b4, b3, b2, b1 };
        int rest[8];
    
        f1 = fopen("UAM.txt", "rb");
        fp = fopen("file.txt", "w+");
    
        while ((a = fgetc(f1)) != EOF)
        {
            printf("%d\n", a);
    
            for (i = 0; i <= 7; i++)
            {
                rest[i] = a & mask[i];
            }
    
            for (i = 0; i <= 7; i++)
            {
                rest[i] = rest[i] / mask[i];
            }
    
            a=0;
            for (x = 0; x <= 7; x++)
            {
                printf("%i", rest[x]);
                a += rest[x] * mask[x];
            }
    
            printf("\n%d\n", a);
    
            fputc(rest[x], fp);
    
            printf("\n");
        }
    
        fclose(f1);
        fclose(fp);
    
        return 0;
    }
    

    A better approach could be

    #include
    
    int main(void)
    {
    
        int x, i;
        char a;
    
        FILE *f1, *fp;
    
        int rest[8];
    
        f1 = fopen("UAM.txt", "rb");
        if ( f1 != NULL)
        {
            fp = fopen("file.txt", "w+");
    
            if ( fp != NULL)
            {
                while ((a = fgetc(f1)) != EOF)
                {
                    printf("%d\n", a);
    
                    for (i = 0; i < 8; i++)
                    {
                        rest[i] = a & 0x01;
    
                        a>>=1;
                    }
    
                    a=0;
                    for (x = 7; x >= 0; x--)
                    {
                        printf("%i", rest[x]);
    
                        a += ((0x01u << x) * rest[x]);
                    }
    
                    fputc(rest[x], fp);
    
                    printf("\n");
                }
    
                fclose(fp);
            }
    
            fclose(f1);
        }
    
        return 0;
    }
    

提交回复
热议问题