You don't have to loop through every byte read.
You can do
fread(&(fname->data), sizeof(char), text_length, fptr);
if you know the amount of characters in the file.
Otherwise you can do
int i = 0;
while(!feof(fptr))
{
fread((&(fname->data)) + i, sizeof(char), 1, fptr);
i++;
}
Remember that you must append a null character to the string.
(you can memset the array before using it so it contains only nulls)
Hope this helps.
PS. I edited out a lot of errors haha :)
venomxxl
Junior Poster in Training
72 posts since Jan 2009
Reputation Points: 34
Solved Threads: 7
Really, why would you want to? You know that some of the binary characters have no ascii representation, hence can't be displayed. It would be better to display each binary value in hex, thus displaying each and everyone of them.
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
Alternatively, use isprint to determine if there's a printable representation of the character, and show the numeric value if there is not.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Try compiling this program
testp.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char**argv)
{
char ch;
FILE *fd = NULL;
if ( argc != 2 )
{
fputs("usage error - a.out <Filename>\n", stderr);
exit(EXIT_FAILURE);
}
if (!(fd = fopen(argv[1], "r")))
{
fprintf(stdout, "Could not open %s\n", argv[1]);
exit(EXIT_FAILURE);
}
while (fread(&ch, sizeof(char), 1, fd))
{
fprintf(stdout, "%p ", (void*)ch);
}
fclose(fd);
return 0;
}
Now pass a file name as a command line argument..It should display the binary(hex values) contents of the file.
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
It's a warning and it's quite irrelevant. Every pointer is just a number. The compiler warns you that you might make a mistake (e.g. write 32-bit integers into an array of bytes and make a "buffer overflow").
venomxxl
Junior Poster in Training
72 posts since Jan 2009
Reputation Points: 34
Solved Threads: 7
It's a warning and it's quite irrelevant.
It's a warning, but hardly irrelevant. The warning tells me that either the author made a mistake and meant &ch, or was hoping %p would print a hexadecimal value and was trying to be clever. Either way, the code is wrong. The fix for the latter is to recognize that fprintf already supports hexadecimal output without subverting the type system:
fprintf(stdout, "%3x", ch);
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401