I want to get the Magic Number from a binary file (for example file ELF hava 7f 45 4c 46). I wrote a program to print out the magic number of the file but i get the error zsh: segmentation fault ./magic. How should I fix this?
int main()
{
//setlocale(LC_ALL, "Russian");
//FILE *fp;
//fopen (&fp, "/Documents/OCP/lab1test/lab1call", "rb");
FILE *fp;
long fSize;
fp = fopen("/Documents/OCP/lab1test/lab1call", "rb");
fseek (fp , 0 , SEEK_END);
fSize = ftell (fp);
rewind (fp);
char *magic_number;
magic_number=(char *)malloc(fSize+1);
//unsigned char magic_number[4];
fread(magic_number, sizeof(char), 4, fp);
printf ("A magic number of your file is:\n");
//magic_number[4] = '\0';
//for (int i = 0; i < 4; i++)
printf ("%02hhx%02hhx%02hhx%02hhx\n ", magic_number[0],magic_number[1], magic_number[2], magic_number[3]);
printf("\n");
}
A few things first:
I doubt that
/Documents/OCP/lab1test/lab1callis a valid path on your system. It's usually/home/[USER]/Documents/..., you should double check that. Even better, pass it as an argument to your program so you can dofopen(argv[1], ...)after checking thatargc == 2.You definitely do not need to seek all the way to the end of the file, and you definitely do not need to allocate a buffer the entire size of the file only to read four bytes at the beginning of the file. Simply
fread4 bytes. You can safely declare a 4-byte array on the stack ofmain.You must do error checking. Almost every library function in C can fail and return an error. Check the manual page (usually simply type
man 3 function_namein your terminal) and see which errors can happen for each function and which is a "good" return value. The section3of the manual is for library functions. If you don't have the manual installed you can use an online one like for example manned.org.With this said, what you're trying to do can be simplified down to:
You can compile and then run your program like this:
Beware that if the path contains spaces you will have to enclose it in quotes otherwise it will be interpreted as two different arguments: