简体   繁体   English

遍历时出现“无效参数”错误

[英]“Invalid Argument” error when globbing

I've been trying to use the glob function in C to get a set of filenames in a directory where I store data. 我一直试图在C中使用glob函数在我存储数据的目录中获取一组文件名。 However I keep getting an error message that claims "Invalid Argument". 但是,我不断收到一条错误消息,声称“ Invalid Argument”。 I have no idea what argument it is refering to. 我不知道它指的是什么。 Here is a sample code that produces the error 这是产生错误的示例代码

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <glob.h>

int main(int argc, char *argv[]){
    int j = 0, err = 0;
    glob_t *files = NULL;
    err = glob("*", GLOB_ERR | GLOB_MARK, NULL, files);
    if(err){
        printf("Error found: %s\n",strerror(errno));
        exit(err);
    }
    for(j = 0; j < files->gl_pathc; ++j){
        printf("%s\n",files->gl_pathv[j]);
    }
    return 0;
}

Looking foward for any suggestions 期待任何建议

The way you are currently passing files there is no way glob() could actually populate it. 您当前传递files方式没有glob()实际填充它的方式。 Rather, what you want to do is: 相反,您想要做的是:

glob_t files = { 0 };
err = glob("*", GLOB_ERR | GLOB_MARK, NULL, &files);

You should also call globfree(&files) later to clean up. 您还应该稍后调用globfree(&files)进行清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM