#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void ini(char*, char*);
int main(int args, char* argv[])
{
if(args!=3) {printf("Enter correct format: myls.out . an"); return 0;}
ini(argv[1],argv[2]);
return 0;
}
void ini(char* dir,char* match)
{
DIR* dirp;
dirp = opendir(dir);
if ( dirp == NULL )
{
printf("\ndir open error\n");
exit(1);
} //Error for opening dir
else
{
struct stat fst;
struct dirent* dentry;
dentry = readdir(dirp);
while ( dentry != NULL )
{
if ( !stat(dentry->d_name, &fst) )
{
// report as whether is a directory or regular file
if ( S_ISDIR(fst.st_mode) )
{
if( !strcmp(dentry->d_name,".") || !strcmp(dentry->d_name,"..") );
else
{
char fullpath[1024];
strcpy(fullpath,dir);
strcat(fullpath,"/");
strcat(fullpath,dentry->d_name);
ini(fullpath,match);
}
}
else if ( S_ISREG(fst.st_mode) )
{
if(strstr(dentry->d_name,match)!=NULL)
printf("%s/%s \n",dir,dentry->d_name);
}
}
dentry = readdir(dirp);
}
closedir(dirp);
}
printf("\n");
}
This program takes 2 arguments. Sample run:
./a.out . an
./andy.txt
./subdir/band.out
./subdir/cs337/handy.c
./than.text
When the argument name is a substring of a file's name, display full path and the name of the file. The problem of my code is that it only goes one level down. Can anyone help me? Sample:
./a.out . an
./andy.txt
./subdir/band.out
./than.text
You need to pass fullpath
to stat
, otherwise it's not going to tell you that you are looking at a directory:
while ( dentry != NULL ) {
// Make full path right away
char fullpath[1024];
strcpy(fullpath,dir);
strcat(fullpath,"/");
strcat(fullpath,dentry->d_name);
if ( !stat(fullpath, &fst) ) { // Pass fullpath to stat
// report as whether is a directory or regular file
if ( S_ISDIR(fst.st_mode) ) {
if( !strcmp(dentry->d_name,".") || !strcmp(dentry->d_name,"..") )
;
ini(fullpath,match);
} else if ( S_ISREG(fst.st_mode) && strstr(dentry->d_name,match)!=NULL) {
// Combine two conditions to eliminate "if"
printf("%s/%s \n",dir,dentry->d_name);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.