Implementing the ls -al command in C

前端 未结 5 1907
误落风尘
误落风尘 2021-02-05 09:38

As a part of an assignment from one of my classes, I have to write a program in C to duplicate the results of the ls -al command. I have read up on the necessary materials but I

5条回答
  •  遇见更好的自我
    2021-02-05 09:57

    This is the final code I got to work for anyone interested. It prints the correct file sizes. Credit goes to asker and mux for answering, just putting the code together. Input I got this to work for is "./main ." .

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char* argv[])
    {
        DIR *mydir;
        struct dirent *myfile;
        struct stat mystat;
    
        char buf[512];
        mydir = opendir(argv[1]);
        while((myfile = readdir(mydir)) != NULL)
        {
            sprintf(buf, "%s/%s", argv[1], myfile->d_name);
            stat(buf, &mystat);
            printf("%zu",mystat.st_size);
            printf(" %s\n", myfile->d_name);
        }
        closedir(mydir);
    }
    

提交回复
热议问题