简体   繁体   中英

Dir pointers to access dir and files information with stat

I am a novice C programmer. I am attempting to open a dir and read those files name and use stat to give me info on those files.Here I am just trying to see if they are Directories or files. Later Ill get modified time and the size of the files etc. as of now I am only getting one level in, so the info for . and .. files. why?

./check Dirc
whats in Dirc
two dir and two files
Program/ ProgramX/ test test2



Dir *ptrDir;
struct dirent *stDir;
struct stat buff;
if( ptrDir = opendir( argv[1] ) !=NULL){
    printf("%s\n",argv[1]);
    while( (stDir = readdir( ptrDir )) != NULL){
        if(stDir->d_name[0] !='.'){//i dont want the hidden files
            if( (stDir->d_name, &buff) == -1){ perror("stat broke");} 
            printf("stDir name: %s\n", stDir->d_name);
            switch(buff.st_mode &s_IFMT){
                case S_IFDIR: printf("Directory\n"); break;
                case S_IFREG: printf("File\n"); break;
                default: print("default\n");
            }
        }
 }
}




OutPut:
Data:
stDir name: Program
stat broke: No such file or directory


Expected OutPut:
OutPut:
Data:
stDir name: Program
Directory
stDir name: ProgramX
Directory
stDir name: test
File
stDir name: test2
File

So I should have read the man pages better. Really what I was not doing was checking if a file found was not '.' in front, if it was not then take that file and build the path to place in stat.

while ( (stDir = readdir(pDir)) != NULL) {
            char * ePath =  malloc(strlen(Data));
            strcpy(ePath,Data);
            strcat(ePath,stDir->d_name);
    if (oneFlag[1] == 'a'){
            printf("    %10s\n", stDir->d_name);
    } else if (oneFlag[1] == 'l') {
        if (stDir->d_name[0] != '.') {
   //printf("ePath value %s \n",ePath);
            if( stat( ePath, &buff) == -1){   perror("perror-stat broke"); exit(-1);  }....

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM