I am trying to find out filetypes using c code, here is the code
char *get_file_type(char *path, char *filename)
{
FILE *fp;
char command[100];
char file_details[100];
char *filetype;
sprintf(command, "file -i %s%s", path, filename);
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
while (fgets(file_details, sizeof(file_details)-1, fp) != NULL) {
filetype = (strtok(strstr(file_details, " "), ";"));
}
pclose(fp);
return filetype;
}
here instead of declaring command[], can I use *command? I tried to use it, but it throwed an exception. we dont need to free up variables declared like command[]? if yes how?
You can use
char *command;, but then, you must allocate some memory forcommandto refer to with a call tomalloc()and when you are done ith that memory, it has to be freed again with a call tofree().As you can see, that is a lot more work than using a fixed-size array (as you do now), but it can be made a lot safer as well, because you could create a buffer of exactly the right size, instead of hoping that the total length of the command won’t exceed 100 characters.
Aside from that, your code has a problem: The
filetypepointer that the function returns points to a location within the arrayfile_details, but that array will be cleaned up by the compiler when executing thereturnstatement, so the pointer that gets returned by the function refers to some memory that is marked as “free to be used for other purposes”.If it is not a problem that the result of
get_file_typeis only valid for one file at a time, you can declare thefile_detailsarray asstatic, so that it will be preserved across calls to the function.