I am using the stat.h header and stat() to read and list files and directories in a directory. I've tried my code with different preset directories to see the result and print the corresponding type of the entry and so far in each test the code shows the current directory and 2 sub directories as directories but shows the other directories as files despite having the correct path listed alongside it
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <locale.h>
#include <sys/stat.h>
#include <wchar.h>
extern int errno;
int main(int argc, char *argv[]) {
setlocale(LC_ALL,"Turkish");
DIR* dp;
struct dirent dirp;
char test[9999];
getcwd(test,9999);
printf("FOLDERMAIN:%s\n",test);
dp=opendir(".");
searchDirectoryForString(dp,"Mat",test);
return 0;
}
void searchDirectoryForString(DIR* dp,char* str,char* directoryname)
{
int lineno=1,num=0;
FILE* fp;
struct dirent *file;
char temp[99999];
char buf[99999];
char *rpath;
rpath = calloc(99999,1);
char path[99999];
char* temppath;
temppath = calloc(99999,1);
int count = 0;
char dirhold[100];
char* dot;
int line_num = 1;
int find_result=0;
static int check=0;
DIR* fdp;
if(dp==NULL)
{
printf("cant open");
}
struct stat filestat;
while (file=readdir(dp)) {
stat(file->d_name,&filestat);
//printf("%s\n",file->d_name);
if(strcmp(file->d_name,"..")==0||(strcmp(file->d_name,".")==0))
continue;
if ( S_ISDIR(filestat.st_mode))
{
check ;
printf("\n CHECK: %d\n",check);
if(check!=1)
{
strcpy(temppath,directoryname);
printf("temp:%s\n",directoryname);
strcat(directoryname,"\\");
strcat(directoryname,file->d_name);
dot = strrchr(directoryname, '\\');
strcpy(dirhold,dot);
printf("DIR: %s\n",dirhold);
printf("%s KLASÖR\n",directoryname);
chdir(directoryname);
dp=opendir(directoryname);
if(dp==NULL)
{
printf("2\n");
}
strcat(temppath,dirhold);
searchDirectoryForString(dp,str,temppath);
}
else{
strcpy(path,directoryname);
strcat(directoryname,"\\");
strcat(directoryname,file->d_name);
dot = strrchr(directoryname, '\\');
strcpy(dirhold,dot);
printf("DIR: %s\n",dirhold);
printf("%s FOLDER\n",directoryname);
chdir(directoryname);
dp=opendir(directoryname);
if(dp==NULL)
{
printf("2\n");
}
strcat(path,dirhold);
searchDirectoryForString(dp,str,path);
}
}
else
{
snprintf(buf,99999,"%s",directoryname);
strcat(buf,"\\");
//strcat(directoryname,dirhold);
strcat(buf,file->d_name);
printf("%s FILE \n",buf);
//Close the file if still open.
if(fp) {
fclose(fp);
strcpy(rpath," ");
}
}
}
}
}
I tried my best to produce an MCVE below. One new thing i noticed is if i add another folder to a preset folder it is not recognized as a folder. If i add a folder to a folder which is one of the recognized folders it is also recognized as a folder(nested folder) the issue is most likely caused by the stat function so wrote another function for it to be able to seen more clearly as its in its own scope. Im using devc as my IDE.
#include <locale.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <wchar.h>
int main(int argc, char *argv[]) {
setlocale(LC_ALL,"Turkish");
DIR* dp;
struct dirent dirp;
char test[9999];
getcwd(test,9999);
printf("FOLDERMAIN:%s\n",test);
dp=opendir(".");
listDir(dp,test);
return 0;
}
int isDir(const char *name) {
struct stat fileStat;
return !stat(name, &fileStat) && S_ISDIR(fileStat.st_mode);
}
void listDir(DIR* dp,char* directoryname)
{
struct dirent *file;
char buf[99999];
char* temppath;
temppath = calloc(99999,1);
int count = 0;
char dirhold[100];
char* dot;
int line_num = 1;
int find_result=0;
static int check=0;
char* dir;
DIR* fdp;
if(dp==NULL)
{
printf("cant open");
}
while (file=readdir(dp)) {
//printf("%s\n",file->d_name);
if(strcmp(file->d_name,"..")==0||(strcmp(file->d_name,".")==0))
continue;
if (isDir(file->d_name))
{
check ;
printf("\n CHECK: %d\n",check);
strcpy(temppath,directoryname);
printf("temp:%s\n",directoryname);
strcat(directoryname,"\\");
strcat(directoryname,file->d_name);
dot = strrchr(directoryname, '\\');
strcpy(dirhold,dot);
printf("DIR: %s\n",dirhold);
printf("%s FOLDER\n",directoryname);
chdir(directoryname);
dp=opendir(directoryname);
if(dp==NULL)
{
printf("2\n");
}
strcat(temppath,dirhold);
listDir(dp,temppath);
}
else
{
snprintf(buf,99999,"%s",directoryname);
strcat(buf,"\\");
strcat(buf,file->d_name);
printf("%s FILE\n",buf);
}
}
}
CodePudding user response:
This is my code that does more or less what you want. It is also available in my SOQ (Stack Overflow Questions) repository on GitHub as file dirlist43.c
in the src/so-7406-2431 sub-directory.
What went wrong in the MCVE code?
There were a fairly large number of problems, including:
Not much error checking for failed calls.
Changing directory with changing back correctly.
No debug code to help determine what is going wrong.
Too many places where
opendir()
was called.Too many places where the result of
opendir()
was checked — one of them in a different function from where the call was made.Missing headers.
Unused variables.
Not reporting errors on
stderr
.Confusion about
directoryname
vstemppath
.Sequencing of
chdir()
calls worked downwards, once. But there was no code to change back after finishing a directory.Missing
closedir()
— I ran out of file descriptors when run on a directory with about 3000 sub-folders.More debatable: I've used
snprintf()
orprintf()
to concatenate strings. For raw performance, you may find thatstrcpy()
andstrcat()
are quicker, but usingstrcat()
can slow things down as it scans from the start of the string each time. Clever code determines the length of the string so that you can copy each time you append, but the Standard C functions aren't helpful for that.
And notes from another comment:
- Note that using
chdir()
is error prone — doubly so if there are symlinks lurking around — and should be avoided when possible. (This was an accurate comment.) - You have a large number of occurrences of 99999 (and some occurrences of 9999); there should be a macro (or enumeration constant) for that value.
- On Unix systems, you must
#include <errno.h>
and should never declareextern int errno;
becauseerrno
is typically not a simple variable but rather an expression that evaluates to a per-threadint
value. I think the same is true on Windows.
Other solutions
In a comment, I noted that:
If you were coding on a Unix (POSIX) system, it would be an odds-on bet that the problem and the fixes are described in
stat()
error "no such file or directory when file name is returned byreaddir()
. Even on Windows, you are likely to be running into similar problems. However, there are Windows-specific APIs to process directories that could be used instead ofreaddir()
.
Since your MCVE code uses Windows-style \
path separators but compiles, the majority of the advice in that question is valid. Note that POSIX provides some functions — fstatat()
and dirfd()
— that avoid messing around with chdir()
. This is advantageous, especially in threaded programs as chdir()
changes directory for all threads at the same time, which is apt to cause chaos if the different threads are accessing files in different directories identified by relative rather than absolute pathnames.
Code: dirlist43.c
#include <dirent.h>
#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef UNIX
#define DIRSEP_STR "/"
#define DIRSEP_CHR '/'
#else
#define DIRSEP_STR "\\"
#define DIRSEP_CHR '\\'
#endif
#define PATH_LEN 99999
extern void listDir(const char *directoryname);
extern int isDir(const char *name);
int main(void)
{
setlocale(LC_ALL, "Turkish");
char pwd[PATH_LEN];
getcwd(pwd, sizeof(pwd));
printf("FOLDERMAIN: %s\n", pwd);
listDir(pwd);
return 0;
}
int isDir(const char *name)
{
struct stat fileStat;
int rc = stat(name, &fileStat) == 0 && S_ISDIR(fileStat.st_mode);
#ifdef DEBUG
printf("%s(): %d [%s]\n", __func__, rc, name);
#endif /* DEBUG */
return rc;
}
#ifdef DEBUG
static void chk_pwd(const char *tag)
{
char pwd[PATH_LEN];
if (getcwd(pwd, sizeof(pwd)) == 0)
{
int errnum = errno;
fprintf(stderr, "%s(): getcwd() failed: %d %s\n",
__func__, errnum, strerror(errnum));
exit(1);
}
printf("PWD: %s [%s]\n", tag, pwd);
}
#else
#define chk_pwd(tag) ((void)0)
#endif /* DEBUG */
static void set_pwd(const char *directoryname)
{
#ifdef DEBUG
printf("CHDIR 1: [%s]\n", directoryname);
#endif /* DEBUG */
if (chdir(directoryname) != 0)
{
int errnum = errno;
fprintf(stderr, "%s(): chdir(%s) failed: %d %s\n",
__func__, directoryname, errnum, strerror(errnum));
exit(1);
}
chk_pwd("CHDIR 1");
}
void listDir(const char *directoryname)
{
#ifdef DEBUG
static int level = 0;
#endif /* DEBUG */
static int check = 0;
#ifdef DEBUG
printf("-->> %s() level %d (%s)\n", __func__, level, directoryname);
#endif /* DEBUG */
DIR *dp = opendir(directoryname);
if (dp == NULL)
{
perror(directoryname);
return;
}
set_pwd(directoryname);
struct dirent *file;
while ((file = readdir(dp)) != NULL)
{
if (strcmp(file->d_name, "..") == 0 || (strcmp(file->d_name, ".") == 0))
continue;
if (isDir(file->d_name))
{
printf("CHECK: %d\n", check);
char temppath[PATH_LEN];
snprintf(temppath, sizeof(temppath), "%s%s%s",
directoryname, DIRSEP_STR, file->d_name);
printf("FOLDER: %s\n", temppath);
chk_pwd("Before recursion");
listDir(temppath);
set_pwd(directoryname);
chk_pwd("After recursion");
}
else
{
printf("FILE: %s%s%s\n", directoryname, DIRSEP_STR, file->d_name);
}
}
closedir(dp);
#ifdef DEBUG
printf("<<-- %s() level %d (%s)\n", __func__, level--, directoryname);
#endif /* DEBUG */
}
It can be compiled with -DUNIX
if you work on a POSIX-like system where slash /
is used to separate path components, or without if you work on a Windows-like system where backslash \
is used. It can be compiled with -DDEBUG
to get copious extra debugging output.
The makefile
is configured for Unix — the code was tested on a MacBook Pro running macOS Big Sur 11.7.