Reputation: 6092
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?
Upvotes: 7
Views: 54947
Reputation: 7074
When you declare an array:
char command[100];
the compiler allocates the memory for it (100 chars in this case) and command
points to the start of that memory. You can access the memory you've allocated:
command[0] = 'a'; // OK
command[99] = 'A'; // OK
command[100] = 'Z'; // Error: out of bounds
but you cannot change the value of command
:
command = NULL; // Compile-time error
The memory will be automatically freed when command
goes out of scope.
When you declare a pointer:
char *commandptr;
you only create a single variable for pointing to char
s, but it doesn't point to anything yet. Trying to use it without initialising it is an error:
commandptr[0] = 'A'; // Undefined behaviour; probably a segfault
You need to allocate the memory yourself using malloc
:
commandptr = malloc(100);
if (commandptr) {
// Always check that the return value of malloc() is not NULL
commandptr[0] = 'A'; // Now you can use the allocated memory
}
and free it when you've finished with it:
free(commandptr);
Upvotes: 15
Reputation: 15768
You can use char *command;
, but then, you must allocate some memory for command
to refer to with a call to malloc()
and when you are done ith that memory, it has to be freed again with a call to free()
.
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 filetype
pointer that the function returns points to a location within the array file_details
, but that array will be cleaned up by the compiler when executing the return
statement, 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_type
is only valid for one file at a time, you can declare the file_details
array as static
, so that it will be preserved across calls to the function.
Upvotes: 6
Reputation: 6233
Why would you change it? For temporary buffers, people usually declare the arrays with [] so they don't have to worry about garbage disposal.
Upvotes: 1