c - while 循环和 if 与 C 中的 readdir() 相处不好

标签 c

在尝试编写一个程序来搜索目录并列出与命令行参数匹配的内容时,我遇到了一个我似乎无法弄清楚的问题。

我在 while 循环中放置了一个 if 语句来检查字符串是否匹配,但问题是我只能获取目录中的最后一个条目。如果我注释掉 if 语句,它会很好地打印整个目录,并且它会很好地匹配字符串,但它不会同时执行这两项操作。

一位 friend 建议它与堆栈有关,但由于它在每次读取后都会打印,我不明白为什么会这样。

DIR *dirPos;
struct dirent * entry;
struct stat st;
char *pattern = argv[argc-1];

//----------------------
//a few error checks for command line and file opening
//----------------------

//Open directory
if ((dirPos = opendir(".")) == NULL){
    //error message if null
}

//Print entry
while ((entry = readdir(dirPos)) != NULL){
    if (!strcmp(entry->d_name, pattern)){
        stat(entry->d_name, &st);
        printf("%s\t%d\n", entry->d_name, st.st_size);
    }
}

最佳答案

entry 必须定义为指针。 struct dirent* 条目。我在 c 上编译了这个,它运行得很好。

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

int main( int argc, char **argv )
{
    DIR *dirPos;
    struct dirent* entry;
    struct stat st;
    char *pattern = argv[argc-1];

    //----------------------
    //a few error checks for command line and file opening
    //----------------------

    //Open directory
    if ((dirPos = opendir(".")) == NULL){
        //error message if null
    }

    //Print entry
    while ((entry = readdir(dirPos)) != NULL){
        if (!strcmp(entry->d_name, pattern)){
            stat(entry->d_name, &st);
            printf("%s\t%d\n", entry->d_name, st.st_size);
        }
    }

    return 0;
}

关于c - while 循环和 if 与 C 中的 readdir() 相处不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651705/

相关文章:

c - 如何从tree-sitter中的节点获取值?

c - 使用链接器命令将 C 中的数组分配到特定位置

c - 如何通过 COM 接口(interface)以编程方式激活 OLE 控件?

c - Galois LFSR - 如何指定输出位数

c - 为什么这个宏编译器依赖?

c - 编写C代理时出现的问题

c - 如果不是从键盘, scanf() 从哪里读取输入?

c - C 中的有符号 vs 无符号 int

c - 当我们用正常的内存分配替换/dev/mem 映射时,8 位内存访问的行为如何

实现我自己的malloc函数的C代码