本文介绍了当前工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一些代码,这些代码遍历列出所有文件、路径和文件大小的目录.我现在坚持遍历过程的最后一部分,即使代码进入任何遇到的目录的 if 语句.

I am currently building some code that traverses through directorys listing all files and paths and file sizes. I am now stuck with the final part of the traverse process which is the if statement to make the code go into any encountered directories.

do {
    char *filename = entry->d_name;
    stat(filename,&buffer);
    if (S_ISDIR(buffer.st_mode)) {
        name = entry->d_name;
        chdir(name);
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;
        listdir(name);     //THIS IS THE NAME OF THE FUNCTION THAT THIS SNIPPET IT FROM!
        chdir("..");
    }
    else
        printf("%s\t%d\n", entry->d_name,buffer.st_size);

试图将它 cd 到它遇到的目录中,我感到很困惑!啊!

Am so confused by trying to get it to cd into the directory that it encounters! ARGH!

推荐答案

问题,当我执行时,stat() 失败了.

The problem, when I executed, was stat() was failing.

这对我有用:

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

void listdir(const char* const name);

int main(void)
{
    listdir(getenv("PWD"));
    return 0;
}

void listdir(const char* const name)
{
    DIR *dir;
    struct dirent *entry;
    struct stat buffer;
    char* path = 0;

    if (!(dir = opendir(name)))
        return;
    if (!(entry = readdir(dir)))
        return;

    do {
        path =
            malloc((strlen(name) + strlen(entry->d_name) + 2) * sizeof(char));
        sprintf(path, "%s/%s", name, entry->d_name);

        if (-1 == stat(path,&buffer))
        {
            fprintf(stderr, "stat(%s) failed: %s\n",
                path, strerror(errno));
            exit(1);
        }
        else if (S_ISDIR(buffer.st_mode))
        {
            if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
            {
                listdir(path);
            }
        }
        else
        {
            printf("%s\t%d\n", path, buffer.st_size);
        }
        free(path);
    } while (entry = readdir(dir));
    closedir(dir);
}

删除对 chdir() 的调用,因为意识到它是多余的.这确实提供了列表,但不使用 chdir() 来实现.

Removed call to chdir() as realised it was superfluous. This does provide listing but does not do it using chdir().

这篇关于当前工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:40