ank*_*000 16 c linux ls file stat
作为我的一个类的赋值的一部分,我必须在C中编写一个程序来复制ls -al命令的结果.我已经阅读了必要的材料,但我仍然没有得到正确的输出.这是我的代码到目前为止,它只应打印出文件大小和文件名,但其打印的文件大小不正确.
码:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char* argv[])
{
    DIR *mydir;
    struct dirent *myfile;
    struct stat mystat;
    mydir = opendir(argv[1]);
    while((myfile = readdir(mydir)) != NULL)
    {
        stat(myfile->d_name, &mystat);    
        printf("%d",mystat.st_size);
        printf(" %s\n", myfile->d_name);
    }
    closedir(mydir);
}
这些是执行代码后的结果:
[root@localhost ~]# ./a.out Downloads
4096 ..
4096 hw22.c
4096 ankur.txt
4096 .
4096 destination.txt
这是正确的尺寸:
[root@localhost ~]# ls -al Downloads
total 20
drwxr-xr-x.  2 root root 4096 Nov 26 01:35 .
dr-xr-x---. 24 root root 4096 Nov 26 01:29 ..
-rw-r--r--.  1 root root   27 Nov 21 06:32 ankur.txt
-rw-r--r--.  1 root root   38 Nov 21 06:50 destination.txt
-rw-r--r--.  1 root root 1139 Nov 25 23:38 hw22.c
任何人都可以指出我的错误.
谢谢,
ANKUR
iab*_*der 14
myfile->d_name是文件名没有路径,所以你需要将文件名添加到目录"Downloads/file.txt"第一,如果它不工作目录:
char buf[512];    
while((myfile = readdir(mydir)) != NULL)
{
    sprintf(buf, "%s/%s", argv[1], myfile->d_name);
    stat(buf, &mystat);
....
至于为什么它打印的4096是链接的大小.和..上次调用的大小stat().
注意:你应该分配一个足够大的缓冲区来保存目录名,文件名是NULL字节和分隔符,就像这样
strlen(argv[1]) + NAME_MAX + 2;
小智 6
这是我为有兴趣的人工作的最终代码.它打印正确的文件大小.感谢求问者和多路复用者回答,只是把代码放在一起.我得到的输入是"./main"..
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
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);
}