How to list first level directories only in C?

后端 未结 5 1033
清歌不尽
清歌不尽 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:35

    Another less low-level approach, with system():

    #include 
    
    int main(void)
    {
        system("/bin/ls -d */");
        return 0;
    }
    

    Notice with system(), you don't need to fork(). However, I recall that we should avoid using system() when possible!


    As Nomimal Animal said, this will fail when the number of subdirectories is too big! See his answer for more...

提交回复
热议问题