From this post https://stackoverflow.com/a/22059317/5859944
FILE *fileptr;
char *buffer;
long filelen;
fileptr = fopen("myfile.txt", "rb"); // Open the file in binary mode
fseek(fileptr, 0, SEEK_END); // Jump to the end of the file
filelen = ftell(fileptr); // Get the current byte offset
in the file
rewind(fileptr); // Jump back to the beginning of
the file
buffer = (char *)malloc((filelen+1)*sizeof(char)); // Enough memory
for file + \0
fread(buffer, filelen, 1, fileptr); // Read in the entire file
fclose(fileptr); // Close the file
You read a file as a byte array.
As it is clear that it is nothing but a string. One could add a
buffer[filelen] = '\0';
and
printf("%s" , buffer);
should print the entrire contents of a file as if it were a string. And it does so in simple text files but not in binary ones.
For binary files , one has to write a function as follows:
void traverse(char *string ,size_t size){
for(size_t i=0;i<size;i++)
printf("%c",string[i]);
}
and print each character one by one. Which puts gibberish on the screen.
- Why
printf
doesn't treatbuffer
as a character string incase of binary files? - Why
printf
in functiontraverse
puts gibberish instead of characters?
For the second bullet point, I know that it maybe due to signed char
but even if the string is stored as unsigned char
results are still the same.