linux - ERROR: stat: No Such File Or Directory, opendir() and stat() in C programming -
hey , reading.
i making program takes 1 argument (directory) , reads files in directory used opendir()/readdir(), , displays file type (reg, link, directory etc) using stat. receiving error "no such file or directory" when execute me program in shell (i using redhat linux). here code:
#define _bsd_source #include <stdio.h> #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { dir *dirp; struct dirent* dent; struct stat info; //if no args if(argc == 1){ argv[1] = "."; dirp=opendir(argv[1]); // specify directory here: "." "current directory" { dent = readdir(dirp); if (dent) { ////////////////////////////////////////////////////////////////////////// if (stat(dent->d_name, &info) == -1) { perror("stat"); exit(exit_failure); } switch (info.st_mode & s_ifmt) { case s_ifblk: printf("block device\n"); break; case s_ifchr: printf("character device\n"); break; case s_ifdir: printf("dir "); break; case s_ififo: printf("fifo/pipe\n"); break; case s_iflnk: printf("lnk "); break; case s_ifreg: printf("reg "); break; case s_ifsock: printf("socket\n"); break; default: printf("unknown?\n"); break; } ////////////////////////////////////////////////////////////////////////// printf("%s \n", dent->d_name); } } while (dent); closedir(dirp); } //////////////////////////////////////////////////////////////////////////////////////////////// //if specified directory if(argc > 1){ dirp=opendir(argv[1]); // specify directory here: "." "current directory" { dent = readdir(dirp); if (dent) { ///////////////////////////////////////////////////////////////////////////////////// if (stat(dent->d_name, &info) == -1) { perror("stat"); exit(exit_failure); } switch (info.st_mode & s_ifmt) { case s_ifblk: printf("block device\n"); break; case s_ifchr: printf("character device\n"); break; case s_ifdir: printf("dir "); break; case s_ififo: printf("fifo/pipe\n"); break; case s_iflnk: printf("lnk "); break; case s_ifreg: printf("reg "); break; case s_ifsock: printf("socket\n"); break; default: printf("unknown?\n"); break; } ////////////////////////////////////////////////////////////////////////////////////// // printf("%s\n", argv[1]); printf("%s \n", dent->d_name); } } while (dent); closedir(dirp); } return 0; }
any ideas? i'm bit stuck. input
also, files of type "link" going output using stat, or have use lstat? not sure how use lstat in situation, if change struct type "struct lstat info" throws error.
dent->d_name
name of file relative current directory (e.g "/home/barney/myfile.txt") not absolute full path file (e.g. /home/barney/sources/myfile.txt), 1 expected stat.
this why stat cant find path. print dent->d_name
before each call stat observe incorrect paths.
edit: can try chdir() change working directory argv[1]
Comments
Post a Comment