How to list first level directories only in C?

后端 未结 5 1053
清歌不尽
清歌不尽 2020-12-19 21:49

In a terminal I can call ls -d */. Now I want a c program to do that for me, like this:

#include 
#include          


        
5条回答
  •  被撕碎了的回忆
    2020-12-19 22:24

    Just call system. Globs on Unixes are expanded by the shell. system will give you a shell.

    You can avoid the whole fork-exec thing by doing the glob(3) yourself:

    int ec;
    glob_t gbuf;
    if(0==(ec=glob("*/", 0, NULL, &gbuf))){
        char **p = gbuf.gl_pathv;
        if(p){
            while(*p)
                printf("%s\n", *p++);
        }
    }else{
       /*handle glob error*/ 
    }
    

    You could pass the results to a spawned ls, but there's hardly a point in doing that.

    (If you do want to do fork and exec, you should start with a template that does proper error checking -- each of those calls may fail.)

提交回复
热议问题