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

后端 未结 3 715
鱼传尺愫
鱼传尺愫 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:39

    Problem #1:

    You call fclose inside the loop which is of cause bad as you are still trying to write to the file. Move the fclose outside the while loop.

    Problem #2:

    while (!feof(f1))
    

    is not the correct way to check if the end-of-file has been reached. Instead you should check the return value from getc Like:

    while ((a = getc(f1)) != EOF)
    

    Problem #3:

    You can't write the binary values one by one to the output file to reproduce the original char. fputc writes a whole char - not a bit. Therefore you need to rebuild the original char from the binary values and only call fputconce.

    Alternative binary calculation

    Your code calculates the binary representation (bit values) correct. However, it seems that you use a too complicated method. Consider using >> (aka right shift) instead. Like:

        // Create the binary values
        for (i = 7; i >= 0; i--)
        {
          rest[i] = a & 1;
          a = a >> 1;
        }
    

    So putting it all together, the code could be:

    int main(void)
    {
    
        int i;
        char a;
        int t;
        FILE *f1, *fp;
        int rest[8];
    
        f1 = fopen("UAM.txt", "rb");   // TODO: check that fopen went well
        fp = fopen("file.txt", "w+");  // TODO: check that fopen went well
    
        while ((a = getc(f1)) != EOF)
        {
            printf("Char representation %c\n", a);
            printf("Decimal representation %d\n", a);
    
            // Create the binary values
            for (i = 7; i >= 0; i--)
            {
              rest[i] = a & 1;
              a = a >> 1;
            }
    
            printf("Binary representation: ");
            for (i = 0; i <= 7; i++)
            {
              printf("%d", rest[i]);
            }
            printf("\n");
    
            // Reconstruct original value
            t = 0;
            for (i = 0; i <= 7; i++)
            {
              t = t << 1;
              t = t | rest[i];
            }
    
            // Write reconstructed value to file
            fputc(t, fp);
        }
    
        fclose(fp);
        fclose(f1);
        return 0;
    }
    

提交回复
热议问题