C 打开和读取目​​录

C opening and reading directories

所以我想用 C 编写一个程序,它的工作方式类似于 Linux 中的 ls 命令, 目前我已经能够列出我当前工作目录中的文件和目录,但我似乎无法对不是我的 CWD 的目录执行相同的操作,我需要在开始之前更改它吗上市了吗?或者函数 opendir() 是否适用于任何目录? 它必须像 Linux 中的 ls -li 一样工作,但我处理了打印内容。 一般来说,我的程序看起来像这样(显然它有更多的东西):

void function(char *directory_to_list){

DIR *d;
struct dirent *dirp;
struct stat filestat;

 if ( (d = opendir(directory_to_list)) == NULL){
    //print error
 }
 while ( ( dirp = readdir(d) ) != NULL){
    //here i call the stat() function for every entry to get various  information
    if (stat(dirp->d_name, &filestat) == -1){
       continue;
     }
    //various prints 
 }
 closedir(d);


}

编辑:命令是 -> ls -li [-dir] 所以如果你没有得到任何目录,你只需列出你的 CWD。

EDIT2:没有返回错误它只是什么都不做,它打开目录很好但是没有列出任何东西所以我猜 stat 调用没有做好,还添加了我如何调用 stat() 的行.

这是一个工作版本。请特别注意不要溢出缓冲区。您必须进行一些重要的错误检查以确保安全:

#include <stdio.h>
#include <dirent.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

int function(char *);

int main(void)
{
    function("/tmp");
    return 0;
}


int function(char *path)
{
    DIR *dir;
    struct dirent *dentry;
    struct stat filestat;
    char *giantbuffer = malloc(sizeof(char) * ((PATH_MAX * 2 ) + 1) );

    if ( ( dir = opendir(path) ) )
    {
         dentry = readdir(dir);
         while ( dentry )
         {

              sprintf(giantbuffer, "%s/%s", path, dentry->d_name);
              printf("%s  ", giantbuffer);

              if (stat(giantbuffer, &filestat) == 0)
                  printf("%zu\n", filestat.st_size);

              dentry = readdir(dir);
         }
         closedir(dir);
    }
    else
        return -1;

    return 0;
}