> 文档中心 > note: expected ‘int’ but argument is of type ‘DIR *’ {aka ‘struct __dirstream *’}记录用close关闭文件夹出错的解决过

note: expected ‘int’ but argument is of type ‘DIR *’ {aka ‘struct __dirstream *’}记录用close关闭文件夹出错的解决过


warning: passing argument 1 of ‘close’ makes integer from pointer without a cast [-Wint-conversion]这句话的意思是需要赋给close的参数需要进行强制类型转换

源代码如下:

#include #include #include #include int main(){DIR *dir  ; struct dirent *eq  ; //open dir dir = opendir("./")  ; if(dir != NULL){while(eq = readdir(dir)){puts(eq->d_name)   ;}}else{perror("opendir error")  ; }//printf("is%d",dp);close(dir) ; return 0 ; }

错误如下:

a.out..main.c.runmain.c: In function ‘main’:main.c:23:8: warning: passing argument 1 of ‘close’ makes integer from pointer without a cast [-Wint-conversion]   23 |  close(dir) ;      | ^~~      | |      | DIR * {aka struct __dirstream *}In file included from main.c:4:/usr/include/unistd.h:353:23: note: expected ‘int’ but argument is of type ‘DIR *{aka ‘struct __dirstream *}  353 | extern int close (int __fd);      |     ~~~~^~~~

通过分析可以得知,close形参需要获得一个int类型的参数

 int close(int fd)      说明:该函数用来关闭已打开的文件.指定的参数fd为open()creat()打开的文件

而以上我们在调用的时候赋给了一个文件夹的DIR 结构体的指针引用,因此该方式会出错。如何解决该问题呢?最先想到使用强制类型转换来进行,但是明显不对;struct类型包含一大堆各种类型变量不可能转为int类型;通过查询,关闭opendir打开的文件夹可以使用以下方法:
note: expected ‘int’ but argument is of type ‘DIR *’ {aka ‘struct __dirstream *’}记录用close关闭文件夹出错的解决过
于是,进行更改:

#include #include #include #include int main(){DIR *dir  ; struct dirent *eq  ; //open dir dir = opendir("./")  ; if(dir != NULL){while(eq = readdir(dir)){puts(eq->d_name)   ;}}else{perror("opendir error")  ; }//printf("is%d",dp);closedir(dir) ; return 0 ; }

运行结果为:

a.out..main.c.rundir_scan.c...

老江饲料商城