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 <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
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
.
run
main.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打开的文件夹可以使用以下方法:
在这里插入图片描述
于是,进行更改:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
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
.
run

dir_scan.c
.
..
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值