c - 从文件夹中检索文件的属性

标签 c readdir

我正在做一项作业,要求我创建一个类似于 ls 的函数。 我的代码工作正常,但是当涉及到实现

的行为时
ls -l child //where child is a folder

有一个奇怪的行为。

假设我位于“parent”文件夹中,其中有一个子文件夹“child”,其中包含一些文本文件。当我从父文件夹运行程序时,它会找到该文件夹​​并打印出其中文本文件的属性。但是,只有当父文件夹中存在相同的文件时,它才会打印子文件夹中的文件。

这是我正在使用的代码片段

    char CurrDir[100];
    DIR *pDir = NULL;
    struct dirent *pFileNames = NULL;

    getcwd(CurrDir, sizeof(CurrDir))

    strncat(CurrDir, "/", strlen(CurrDir));

    unsigned int CurrDirLen = strlen(CurrDir);
    unsigned int CombSize = CurrDirLen + strlen(argv[1]);

    char SuperCharArr[CombSize];

    for(int i = 0; i < CombSize; ++i)
    {
        if( i < strlen(CurrDir) )
            SuperCharArr[i] = CurrDir[i];
        else
            SuperCharArr[i] = argv[1][i%CurrDirLen];
    }//for

    //insert null character at the end of the character
    SuperCharArr[CombSize] = '\0';

    pDir = opendir( SuperCharArr );
    printf("%s\n", SuperCharArr);

    if( pDir != NULL )
    {
        //Directory detected as pDir is a DirectoryStream
        printf("%s\n", "pDir not null");
        PrintHeader();

        while( (pFileNames = readdir(pDir)) != NULL )
        {
            PrintFileDeails(pFileNames);
        }
    }//if

最佳答案

在我在这里发布的原始代码中,有一个名为 PrintFileDeails(pFileNames) 的函数,它接受直接类型的参数。

在PrintFileDeails()中,有一个检查文件状态的函数,代码如下,

struct stat FileStat;

if( stat(pFileNames->d_name, &FileStat) == -1 )
{
    perror("stat");
    exit(EXIT_FAILURE);
}//if

这行代码会打印出一个错误,他们找不到该文件,并且 AAT 的注释让我再次检查我的代码,因为我怀疑它没有读取正确的文件夹。因此,在我传递了应该从中读取文件的完整路径之后,它工作得很好。因此,代码改为这样。

if( stat(pFullPath, &FileStat) == -1 )
{
    perror("stat");
    exit(EXIT_FAILURE);
}//if

其中 pFullPath 传递了 SuperCharArr 的变量,其中包含要搜索的文件所在的完整路径。

stat() 的手册页也有帮助,可以找到 here

关于c - 从文件夹中检索文件的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26463179/

相关文章:

c - 如何在c中连接多个二维数组

c - termios 在嵌入式设备上截断的串行数据

c - 错误[e46] : Undefined external "set_all_ports" referred in GPIO main

c - readdir() 是否保证订单?

Node.js fs.readdir 递归目录搜索

c++ - “mblctr”不被识别为内部或外部命令、可操作程序或批处理文件。如何解决此问题?

c - 不使用 malloc() 分配 struct dirent

julia - 你能让 Julia 的 readdir() 函数区分文件和目录吗?

PHP opendir 和 readdir 与数组目录(不是一个)

c - 赋值操作真的会返回一些东西吗?