用于在当前目录中打印文件名的C实用程序(Unix) [英] C utility to print filenames in current directory (Unix)
问题描述
对于C和Unix来说还很新。
Fairly new to C and Unix.
我目前有:
#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;
}
有人告诉我:dir.c:15:警告:初始化使指针,不带强制转换的整数
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.
推荐答案
获取当前工作目录名称的标准函数是 getcwd()
,而不是 get_current_dir_name()
。 get_current_dir_name()
是GNU扩展,仅在包含<$ c $之前定义了宏 _GNU_SOURCE
时可用。 c>< unistd.h> ,建议不要使用它。
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.
在您的情况下, _GNU_SOURCE
未定义,因此 get_current_dir_name()
不是已声明函数的名称。因此,当C编译器看到您尝试调用它时,它会生成一个隐式声明。
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.
隐式函数声明在以下位置创建一个声明使用声明函数接受任意数量和类型的参数并返回 int
。因此,在这种情况下,编译器认为将 int
分配给类型为 char *
的变量,因此
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".
隐式声明是C语言不推荐使用的功能,实际上已从C99版本的C语言版本中删除。语言,尽管现代编译器即使在C99模式下仍经常接受(带有警告)它们。即使在C89模式下,我也强烈建议您尽可能提高警告级别,以捕获此类错误,例如 -Wall -Wextra -Werror -pedantic
(如果可以处理的话)。
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.
这篇关于用于在当前目录中打印文件名的C实用程序(Unix)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!