C语言 如何打印出每个目录,但作为路径名?(在正文描述中解释)



这是劳埃德·马克罗洪(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- %sn", 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
...

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

#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("%sn", entry->d_name);
}
}
closedir(dir);
}
int main(void) {
listdir(".","");
return 0;
}

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

有什么理由不打印传递给函数的name吗?

#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/%sn", name, entry->d_name);
}
}
closedir(dir);
}
int main() {
system("mkdir -p dir/dir; touch dir/file dir/dir/file");
listdir(".", 0);
return 0;
}

实时代码可在onlinedbg上找到。

最新更新