Implementing the ls -al command in C

前端 未结 5 1807
误落风尘
误落风尘 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:54

    myfile->d_name is the file name not the path, so you need to append the file name to the directory "Downloads/file.txt" first, if it's is not the working directory:

    char buf[512];    
    while((myfile = readdir(mydir)) != NULL)
    {
        sprintf(buf, "%s/%s", argv[1], myfile->d_name);
        stat(buf, &mystat);
    ....
    

    As to why it prints 4096 that is the size of the links . and .. from the last call to stat().

    Note: you should allocate a buffer large enough to hold the directory name, the file name the NULL byte and the separator, something like this

    strlen(argv[1]) + NAME_MAX + 2;
    

提交回复
热议问题