I have often used the C function access() to determine if a file exists e.g
if (!access(filename, F_OK))
printf("File exists);
else
printf("File does NOT exist\n");
For my current purposes, I need to be able to tell if a particular SUBDIRECTORY exists.
e..g if I have a subdir "STEVE", and pass "STEVE" to access() it will return 0, but I need to be able to tell if "STEVE" is a subdir, rather than a file. Is there a function that can help me out?
Thanks,
Steve
C
Last Comment
Stephen Kairys
8/22/2022 - Mon
Kent Olsen
Hi Steve,
One of the stat() functions should do nicely.
GoodLuck,
Kent
#include <sys\stat.h>#include <stdio.h>#include <time.h>int main(void){ struct stat statbuf; int handle;// int stat(const char *path, struct stat *statbuf); stat ("c:\\mypath\\dirname", &statbuf); if (statbuf.st_mode & S_S_IFDIR) printf("Directory....\n");}
"The stat() function fills a struct stat structure with information about a specific file; if you've got a file descriptor instead of a file name, you can use the fstat() function instead."
•"S_ISDIR(mode) -- Is this a directory?"
•"S_ISREG(mode) -- Is this a regular file?"
phoffric
Didn't see your post Kent while getting the link and excerpting from it.
>>
S_ISDIR(mode) -- Is this a directory
Not sure I understand this. What is mode?
I see in sys\stat.h that
#define S_ISDIR( m ) (((m) & S_IFMT) == S_IFDIR)
is a macro, but not sure what to pass to it.
Thanks
Stephen Kairys
ASKER
Look like both S_IFDIR and S_ISDIR exist in stat.h
Just to be safe, I first use access() to determine if the file exists: Then I invoke stat...
Please do not assume this code is perfect. I did only cursory testing.
Kent,
Thank you. Your solution had everything in one place so you get the points
phoffric: - As per the above, Kent got the points, but I still appreciate your help. If you feel that you should share in the points, feel free t respond; however, I won't be able to handle your request 'til at least next Thursday as I am going to be on a short vacation. Thanks for your efforts.
phoffric
>> Do they apply to WIndows/DOS 16-bit programming
I didn't realize you were working in Windows/DOS 16-bit programming. And I don't have that product available to test, so I cannot be sure.
But, I tried the kdo's post in VS 2010 Express, and it works fine (with the typo corrected), so that is a good sign that it will work for you.
Since S_ISDIR is defined for you (it is not defined in sys\stat.h in VS 2010 Express), I think the below code should work for you since it works in Linux. However, you need to verify using your DOS-16 system.
if (statbuf.st_mode & S_IFDIR) printf("Directory....\n"); if( S_ISDIR( statbuf.st_mode ) ) printf("S_ISDIR works in Linux\n");
One of the stat() functions should do nicely.
GoodLuck,
Kent
Open in new window