问题
Fairly new to C and Unix.
I currently have:
#include "stdio.h"
#include <dirent.h>
#include <unistd.h>
int main(int argc, char ** argv)
{ char * current = get_current_dir_name(); //where error occurs
DIR * directory = NULL;
directory = opendir(current);
if(directory == NULL)
return -1;
struct dirent * ent;
while((ent = readdir (directory)) != NULL)
printf("%s\n", ent -> d_name);
if(closedir(directory) < 0)
return -1;
}
I'm being told: dir.c:15: warning: initialization makes pointer from integer without a cast
Clearly doing something pretty silly and could use some help.
回答1:
The standard function to get the name of the current working directory is getcwd(), not get_current_dir_name(). get_current_dir_name() is a GNU extension and is only available if the macro _GNU_SOURCE is defined prior to including <unistd.h>, and its use is not recommended.
In your case, _GNU_SOURCE is not defined, so consequently get_current_dir_name() is not the name of a declared function. So when the C compiler sees your try to call it, it generates an implicit declaration.
Implicit function declarations create a declaration at the point of use declaring the function to take an arbitrary number and types of arguments and returning int. Hence, in this case, the compiler thinks it has an int being assigned to a variable of type char*, so it generates the "initialization makes pointer from integer without a cast warning".
Implicit declarations are a deprecated feature of the C language and are in fact removed from the C99 edition of the language, although modern compilers still often accept them (with warnings) even in C99 mode. Even in C89 mode, I highly recommend compiling with your warning level as high as possible to catch errors like this, e.g. -Wall -Wextra -Werror -pedantic if you can handle it.
来源:https://stackoverflow.com/questions/26668409/c-utility-to-print-filenames-in-current-directory-unix