循环遍历文件并在C中打印文件属性

Mik*_*keT 5 c linux posix while-loop

我是C语言编程的新手.我需要这个程序遍历文件夹中的所有文件并为每个文件打印这些属性.此时它正在打印文件夹的属性.

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
    DIR *dp;
    struct stat file_stats;

    if (argc != 2) {
        fprintf(stderr, "Usage: fstat FILE...\n");
        return EXIT_FAILURE;
    }

    if ((stat(argv[1], &file_stats)) == -1) {
        perror("fstat");
        return EXIT_FAILURE;
    }

    dp = opendir("./");
    if (dp == NULL) {
        perror("couldn't open directory");
        return EXIT_FAILURE;
    }

    while (readdir(dp)) {
        printf("filename: %s\n", argv[1]);
        printf(" device: %lld\n",
                file_stats.st_dev);
        printf(" protection: %o\n",
                file_stats.st_mode);
        printf(" number of hard links: %d\n",
                file_stats.st_nlink);
        printf(" user ID of owner: %d\n",
                file_stats.st_uid);
        printf(" group ID of owner: %d\n",
                file_stats.st_gid);
        printf(" device type (if inode device): %lld\n",
                file_stats.st_rdev);
        printf(" total size, in bytes: %ld\n",
                file_stats.st_size);
        printf(" blocksize for filesystem I/O: %ld\n",
                file_stats.st_blksize);
        printf(" inode number: %lu\n",
                file_stats.st_ino);
        printf(" time of last access: %ld : %s",
                file_stats.st_atime,
                ctime(&file_stats.st_atime));
        printf(" time of last change: %ld : %s",
                file_stats.st_ctime,
                ctime(&file_stats.st_ctime));
        closedir(dp);
    }

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

我想我需要将结构移动到while循环中,但是当我这样做时,编译器会说"file_stats unclared".

Val*_*itz 1

你应该打电话

if((stat(ep->d_name, &file_stats)) == -1) {
  perror("fstat");
  return 1;
  } 
Run Code Online (Sandbox Code Playgroud)

在 while 循环内。