gpt4 book ai didi

c - 如何打印每个目录但作为路径名? (在正文描述中解释)

转载 作者:行者123 更新时间:2023-11-30 19:04:09 26 4
gpt4 key购买 nike

这是由 Lloyd Macrohon 编写的代码,所有功劳都属于他,但在过去的两天里,我一直在尝试修改此代码,这样我不想显示目录中每个项目的列表,而是想修改它这样它将每个项目显示为长路径名。

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

void listdir(const char *name, int indent)
{
DIR *dir;
struct dirent *entry;

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

while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char path[1024];
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
printf("%*s[%s]\n", indent, "", entry->d_name);
listdir(path, indent + 2);
} else {
printf("%*s- %s\n", indent, "", entry->d_name);
}
}
closedir(dir);
}

int main(void) {
listdir(".", 0);
return 0;
}

上面是原始代码,在 unix 终端中运行时会输出如下内容:

-file
[directory]
[directory]
-file
-file
-file
....

但是我尝试像这样运行它:

file
directory/directory/file
directory/file
directory/file
...

我的代码版本已经删除了意图,并用一个 char 替换了它们,该 char 包含一个字符,该字符应该是文件之前的路径名。

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>


void listdir(const char *name,const char *pname)
{
DIR *dir;
struct dirent *entry;
char pathn = pname;

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

while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char path[1024];
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
//printf("%s/", entry->d_name);
pathn = pathn + entry->d_name;
listdir(path,pathn);
}
else if( pathn != ""){
printf("%s and %s ", pathn, entry->d_name);
}
else {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
}

int main(void) {
listdir(".","");
return 0;
}

注意:还请原谅我可能错过的任何规定,我不知道未经其他用户许可修改/上传其他用户代码是否违法或违反规则,我对此还很陌生。

最佳答案

是否有任何原因不打印传递给函数的名称

#define _GNU_SOURCE 1
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

void listdir(const char *name, int indent)
{
DIR *dir;
struct dirent *entry;

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

while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char path[1024];
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
//printf("%*s[%s]\n", indent, "", entry->d_name);
listdir(path, indent + 2);
} else {
printf("%s/%s\n", name, entry->d_name);
}
}
closedir(dir);
}

int main() {
system("mkdir -p dir/dir; touch dir/file dir/dir/file");
listdir(".", 0);
return 0;
}

实时代码可在 onlinedbg 获取.

关于c - 如何打印每个目录但作为路径名? (在正文描述中解释),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com