检查目录是否存在时发生段故障 [英] segment fault while Checking if directory exist or not

查看:103
本文介绍了检查目录是否存在时发生段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了这段代码,但它给了我段错误?

 char * path; 

scanf( %20 [^ \ r],路径);
DIR * dir = opendir(路径);
if (dir)
{
printf( 目录存在);
closedir(dir);
}
else if (ENOENT == errno)
{
printf( Directory Exist);
}
else
{
printf( 目录不存在);
}

解决方案

你的路径变量只是一个指向焦炭。但是您必须提供存储扫描字符串的空间,包括终止NULL char:

  char 路径[  21 ]; 


路径必须是缓冲区,而不是char指针。 scanf deposite字符串应该在哪里读取?例如



  char 路径[ 100 ]; 
scanf( %20 [^ \ r],路径);


i used this code but it gives me segment fault ?

char* path;

scanf("%20[^\r]",path);
DIR* dir = opendir(path);
if (dir)
{
printf("Directory Exists");
closedir(dir);
}
else if (ENOENT == errno)
{
printf("Directory Exist");
}
else
{
printf("Directory not Exist");
}

解决方案

Your path variable is just a pointer to char. But you must provide the space to store the scanned string including the terminating NULL char:

char path[21];


path must be a buffer, not a char pointer. Where should scanf deposite string being read? For example

char path[100];
scanf ("%20[^\r]", path);


这篇关于检查目录是否存在时发生段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆