Hey and thanks for reading.
I am making a program which takes 1 argument (directory) and reads all the files in the directory used opendir()/readdir(), and displays the file type (reg, link, directory etc) using stat. I am receiving the error "No Such file or Directory" when I execute me program in the shell (I am using redhat linux). Here is my 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: "." is the "current directory" do { 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: "." is the "current directory" do { 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 a bit stuck. Thanks for your input
Also, are files of type "Link" going to be output using stat, or do I have to use lstat? Not sure how to use lstat in this situation, if I change the struct type to "struct lstat info" it throws an error.