stat()函数只对当前目录有效 C语言

stat() function only works in the current directory C language

我在 windows 上使用 C 来读取目录的内容和每个条目的信息,但是 stat() 函数仅在我打开当前目录“。”时才有效。

directory = opendir(".")

每当我尝试这样的事情时 "C:\Users\User\Desktop\programming" 它不起作用并输出 -1

directory = opendir("C:\Users\User\Desktop\programming")

你能在这里指导我吗

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void perror(const char *str);// for error detail 

int main()
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("C:\Users\User\Desktop\programming");//also C:\Users\User\Desktop\programming\ didn't work
    if ( directory == NULL )
        {
            puts("the directory couldn't be accessed or does not exist");
          return(2);
        }


    printf("No   type         name              size           TimeStamp \n\n");
    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly 
        stat(file->d_name,&info);
        if ((stat(file->d_name,&info)) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }




    return(0);
}

输出图片 link : https://i.stack.imgur.com/tORZU.png

if ( (stat(file->d_name, &info) ) == -1) { ...

file->d_name 仅包含一个包含文件名的字符串,但不包含其路径。 stat() 需要将文件的确切路径作为第一个参数。


尝试:

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

int main (void)
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;
    char* path = "C:\Users\User\Desktop\programming";

    // entering the directory
    directory = opendir(path);

    if ( directory == NULL )
    {
        puts("the directory couldn't be accessed or does not exist");
        return(2);
    }


    printf("No   type         name              size           TimeStamp \n\n");

    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly 

        if (stat(path, &info) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }

    return(0);
}

以下建议代码:

  1. 包括所有需要的 header 文件
  2. 执行所需的功能
  3. 正确检查并处理错误
  4. 正确设置 stat() 函数的路径
  5. 注意:代码来自 /home/richard/documents/forum 目录 运行。这表明建议的代码正确处理了跨目录引用。
  6. 隐藏文件通过忽略以“.”开头的条目而保持隐藏状态

现在,建议的代码

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



int main( void )
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("//home//richard" );
    if ( directory == NULL )
    {
        perror("the directory couldn't be accessed or does not exist");
        return(2);
    }


    printf("No   type         name              size           TimeStamp \n\n");
    while((file = readdir(directory)))
    {
        if( file->d_name[0] == '.' )
        { // then hidden file, so leave hidden
            continue;
        }

        entries++;

        char buffer[1024];
        strcpy( buffer, "//home//richard//" );
        strcat( buffer, file->d_name );
        if (stat( buffer, &info ) == -1)
        {
            perror( buffer );
            continue;
        }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else
            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10ld",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");
    }
    return(0);
}

典型 运行 代码的部分输出是:

No   type         name              size           TimeStamp 

 1  Dir                Music      4096

 2  Dir             projects      4096

 3  Dir         scull-master      4096

 4  Dir         slickeditpro      4096

 5  Dir                 snap      4096

 6  File   clamscanParms.txt       171     Sat May 20 10:06:43 2017

 7  Dir              OpenMPI      4096

 8  Dir        clamav.0.99.2      4096

 9  Dir               Public      4096

10  Dir            Documents      4096

11  Dir              Desktop      4096

12  Dir            Downloads     20480

13  Dir             Pictures      4096

14  Dir            Templates      4096

15  Dir               Videos      4096

16  File        clamscan.log     42952     Tue Feb 18 13:24:58 2020

如您所见,第 header 列和列数据之间的差异仍然存在一些需要更正的差异。我相信你能处理好这个细节。