【问题标题】:When i read the list of files in a diectory i get two files "." and "..", why?当我读取目录中的文件列表时,我得到两个文件“。”和“..”,为什么?
【发布时间】:2021-09-16 00:54:12
【问题描述】:

大家好,我正在编写一个程序 c,它必须读取目录中的文件列表,但是当我打印文件名时,有 2 个文件:“。”和 ”..”。 有什么方法可以防止它在不进行明确检查的情况下读取这两个文件?

我的代码是:

d = opendir("myfolder");
if (d) {
    while((dir = readdir(d)) != NULL){  
        strcpy(path,"myfolder");
        strcat(path,"/");
        strcat(path,dir->d_name);
        printf("File name: %s ",dir->d_name);
    }
    //... other things like closing dir and file.

【问题讨论】:

  • 每个目录都有这两个特殊目录(“当前目录”和“父目录”)。如果您不需要参考它们,只需检查它们并跳过它们。
  • 这是标准的当前目录(对于.)和父目录(对于..)。
  • (另外,strcpy() 和多个低效的strcat() 可以用单个snprintf() 替换)
  • @Shawn 我该怎么做?我的意思是在这种情况下我应该如何使用 snprintf?对不起,我是 C 的新手
  • en.cppreference.com/w/c/io/fprintfsnprintf() 的文档

标签: c file


【解决方案1】:

因为目录中存在具有这些名称的文件。

$ ls -1a
.
..
.bash_history
.bash_logout
.bashrc
  ⋮
bin
projects
tmp
usr
  • . 是指向包含它的目录的硬链接。
  • .. 是指向包含它的目录的父级的硬链接。

大多数时候,您希望忽略名称以“.”开头的文件。

Windows 中的类似想法。

【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 2021-02-23
    • 2020-05-05
    • 2012-01-04
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多