1
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

typedef uint8_t BYTE;

int main(void){

    FILE* open = fopen("open.txt","r");


    BYTE read;

    fread(&read,sizeof(BYTE),1,open);
    FILE* close = fopen("close.txt","w");



    while(!feof(open))
    {

        printf("%2d\n",read);
        fwrite(&read,sizeof(BYTE),1,close);

        fread(&read,sizeof(BYTE),1,open);
    }


    fclose(open);
    fclose(close);


}

2 Answers 2

3

Actually, the program is working exactly as designed. Unfortunately, it isn't what you think. ;-)

If you run the program, it will essentially copy the input file to the output file. Along the way, it will print each char that is read. The reason for your confusion is that you're expecting it to printf what you see in the file. Because of the formatting of %2d in the printf statement, it is printing the ASCII value of each char, not the char itself. So, it prints 32 for spaces, 48 for a 0, 49 for a 1, 10 for a line feed, etc., and prints one ASCII number on each line, followed by a line feed \n.

So, it's doing exactly what it was told to do, just not what you wanted. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • You definitely explain it better ...
    – MARS
    Dec 20, 2016 at 21:10
  • Hey, Actually, I understood the concept after analyzing it again. Anyways, Thanks for the help. @Cliff B Dec 21, 2016 at 11:21
1

The fread and fwrite functions are working fine, as expected, the problems are elsewhere, a somewhat more coherent way of writing your program will be the following:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

typedef uint8_t BYTE;

int main(void)
{
    FILE* open = fopen("open.txt","r");

    BYTE read[10];

    FILE* close = fopen("close.txt","w");

    while(fread(read,sizeof(BYTE),1,open))
    {
        fwrite(read,sizeof(BYTE),1,close);
        printf("%s",read);    
    }

    fclose(open);
    fclose(close);
}

I guess your problem is when trying to print, the read variable is uninitialized and does not have space to print all the contents of the file, as fread advances through the file, in addition as read is actually an unsigned char needs the support "\s"for each character read. Also the use of feof is not correct here, feof returns true if the file cursor is in the end, it returns false in another case. This function is used to know if an attempt was made to read after the end of file, not to know if we are in the end of file. I hope this clarifies your doubts

1
  • 1
    MARS, your version is definitely cleaner and more efficient. However, I would still say that the original version works fine, albeit not quite as efficiently, except that it prints ASCII values instead of chars.
    – Cliff B
    Dec 20, 2016 at 20:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .