Reputation: 11
I'm attempting to write a code which will read a file byte by byte, of any type/format. For starters I want to be able to read and write the same file, but I'm having trouble doing that for any file other than text files.
After searching here, I figured that fread
/fwrite
should work
unsigned char buff;
fopen_s(&input, "input_file_of_any_kind", "r");
fopen_s(&output, "new", "w");
while (!feof(input))
{
fread(&buff, 1, 1, input);
fwrite(&buff, 1, 1, output);
}
fclose(input);
fclose(output);
But when I'm trying to "copy" a jpg or pdf file, it reads only a few bytes (out of KB), so I guess my understanding here is flawed. Could you point me to the right direction? The point of that is to reach the representation of those bytes in bits and manipulate them (and it should work for a file of any size).
Upvotes: 1
Views: 758
Reputation: 153468
To read a file of any size (byte by byte) a simple approach uses fgetc()
.
Open the files in binary and check results.
// fopen_s(&input, "input_file_of_any_kind", "r");
if (fopen_s(&input, "input_file_of_any_kind", "rb")) {
; // Handle error
}
Do not use while (!feof(input))
.
int ch;
while ((ch = fgetc(input)) != EOF) {
fputc(ch, output);
}
Upvotes: 1