Glob in C++ and print the results

こ雲淡風輕ζ 提交于 2019-12-24 12:00:25

问题


I'm just trying to glob everything in a directory and print the list of results, but I get an empty printf:

#include <glob.h>
#include <stdio.h>

int main()
{
  int result;
  glob_t buffer;
  buffer.gl_offs = 10;
  glob("*", GLOB_DOOFFS, NULL, &buffer);
  printf((char*)buffer.gl_pathv);
}

What does work is

printf("%i", buffer.gl_pathc));

回答1:


Do you need to reserve empty slots in glob? Do not include GLOB_DOOFFS if you don't need it. And don't forget to free memory for glob.

Try something like this:

#include <glob.h>
#include <stdio.h>

int main() {

    glob_t globbuf;
    int err = glob("*", 0, NULL, &globbuf);
    if(err == 0)
    {
        for (size_t i = 0; i < globbuf.gl_pathc; i++)
        {
            printf("%s\n", globbuf.gl_pathv[i]);
        }

        globfree(&globbuf);
    }

    return 0;
}


来源:https://stackoverflow.com/questions/15085633/glob-in-c-and-print-the-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!