Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C++/CLI C Linux Ubuntu
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");
}
Posted 6-Feb-13 7:25am
Comments
FatimaAsif at 6-Feb-13 12:28pm
   
i give this input
/home/fatima/Desktop/child
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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];
  Permalink  
Comments
FatimaAsif at 6-Feb-13 12:48pm
   
ok it works thanks for your help.
Jochen Arndt at 6-Feb-13 12:52pm
   
Thank you for your feedback. You may 'Accept' the answer using the so named link to mark it as solved.
FatimaAsif at 6-Feb-13 12:55pm
   
that problem is solved bt another problem is that it only returns Directory exist, how can i solved it , can u please help me?
Jochen Arndt at 6-Feb-13 13:00pm
   
That's another problem. But the answer is easy. Take a close look on your code:
else if (ENOENT == errno)
{
printf("Directory Exist");
}
You are printing "Directory Exist" when it does not exist.
FatimaAsif at 6-Feb-13 14:15pm
   
but if exist or not it gives the same output
Jochen Arndt at 7-Feb-13 1:58am
   
I hope you have seen it meanwhile. The servers where very busy, so that I could not answer. Change your code to:
else if (ENOENT == errno)
{
printf("Directory does not exist");
}
else
{
printf("Not a directory or other error");
}
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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);
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web01 | 2.8.1411022.1 | Last Updated 6 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100