Created
February 7, 2023 00:38
-
-
Save gdetor/1e145342cc2331d88dcc6d1fb44748bf to your computer and use it in GitHub Desktop.
View the content of a binary file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
void print_buffer(void *, int); | |
void catbin(char *); | |
int main(int argc, char **argv) { | |
if (argc == 2){ viewbin(argv[1]); } | |
else{ | |
printf("Please type the name of the binary input file!\n"); | |
printf("Example: viewbin foo.dat \n"); | |
} | |
return 0; | |
} | |
void print_buffer(void *buffer, int buffer_size) { | |
int i; | |
for (i = 0; i < buffer_size; ++i){ | |
printf("%c", ((char *)buffer)[i]); | |
} | |
printf("\n"); | |
} | |
void catbin(char *filename) { | |
FILE *fp; /* Pointer to the input binary file. */ | |
int fileLen; /* File length. */ | |
char *buffer; /* Buffer for temporary storage. */ | |
/* Openning the input binary file and check if the file exists. */ | |
if (!(fp = fopen(filename, "rb"))){ | |
printf("File does not exist!\n"); | |
exit(-1); | |
} | |
/* Calculate the length of the input binary file. */ | |
fseek(fp, 0, SEEK_END); | |
fileLen = ftell(fp); /* The current value of the position indicator. */ | |
fseek(fp, 0, SEEK_SET); | |
/* Memory allocation of the buffer. */ | |
buffer = (char *)malloc(fileLen + 1); | |
/* Read the data from the input binary file and store them temporaly to the buffer. */ | |
fread(buffer, fileLen, 1, fp); | |
fclose(fp); | |
/* Print the data on the standard output. */ | |
print_buffer(buffer, fileLen+1); | |
/* Free allocated memory of the buffer. */ | |
free(buffer); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment