【问题标题】:stat() function only works in the current directory C languagestat() 函数只适用于当前目录 C 语言
【发布时间】:2020-05-31 13:32:39
【问题描述】:

我在 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);
}

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

【问题讨论】:

  • 使用perror 获得额外的错误输出
  • 我用过它显示“没有这样的文件或目录”
  • 顺便说一句,你为什么要给stat(file-&gt;d_name,&amp;info);打两次电话?
  • 错了,虽然不影响代码
  • 关于声明:void perror(const char *str); 原型已经通过:#include &lt;stdio.h&gt; 公开,因此无需编写该原型。

标签: c directory stat


【解决方案1】:

以下建议的代码:

  1. 包含所有需要的头文件
  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

如您所见,列标题和列数据差异之间仍有一些对齐需要更正。我相信你可以处理这个细节。

【讨论】:

  • 好提议,理查德。 +1
  • @user3629249 非常感谢,我知道它现在应该如何工作了。
【解决方案2】:
if ( (stat(file->d_name, &info) ) == -1) { ...

file-&gt;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);
}

【讨论】:

  • 我需要使用“\\”,因为我的编辑器将“\”评估为转义序列
  • @AX360 如果你这样做会发生什么?您收到警告还是错误导致代码无法编译?
  • 它只是将所有条目输出为目录.. 我将在输出的几秒钟内添加一张图片
  • 我的个人资料名称是 User ^_^' ,您可以在图片中的 cmd 窗口标题中看到它
  • 关于:printf("%30s\n",ctime(&amp;info.st_mtime)); 这不会编译,因为代码缺少以下语句:#include &lt;time.h&gt;,因此假定来自ctime() 的返回类型为int 而不是char *跨度>
猜你喜欢
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
相关资源
最近更新 更多