how to printf binary file?
Following code prints me 4 chars, but how to printf whole file?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <stdio.h>
#include <stdlib.h>
char* readFileBytes(const char *name)
{
FILE *fl = fopen(name, "rb");
fseek(fl, 0, SEEK_END);
long len = ftell(fl);
char *ret = (char*) malloc(len);
fseek(fl, 0, SEEK_SET);
fread(ret, 1, len, fl);
fclose(fl);
return ret;
}
int main(){
unsigned char *array = readFileBytes("C:\\ProgramData\\POPWWPROFILES\\rain\\Save14.SAV");
int len = strlen(array);
int i = 0;
for (i;i < len;i++)
{
printf("%X ",array[i]);
}
return 0;
}
|
Last edited on
This is working for me compiling with GCC for windows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readFileBytes(const char *name, int* sz)
{
FILE *fl = fopen(name, "rb");
if(fl == NULL){
printf("Error while opening %s", name);
exit(EXIT_FAILURE);
}
fseek(fl, 0, SEEK_END);
long len = ftell(fl);
*sz = len;
char *ret = (char*) malloc(len);
fseek(fl, 0, SEEK_SET);
fread(ret, 1, len, fl);
fclose(fl);
return ret;
}
int main(){
int* len;
/*unsigned*/ char *array = readFileBytes("C:\\test.txt", len);
//int len = strlen(array);
int i = 0;
//printf("%d", *len);
//exit(0);
for (i; i < *len; i++)
{
printf("%X ",array[i]);
}
free(array);
return 0;
}
|
Last edited on
readFileBytes needs to return the buffer length (as in modoran's version) as you're dealing with a memory block, not a string.
modoran's code in main should be:
1 2 3 4 5 6
|
int main(){
int len;
char *array = readFileBytes("C:\\test.txt", &len);
int i = 0;
for (; i < len; ++i) //...
|
Topic archived. No new replies allowed.