首页 文章

C显示目录内容问题

提问于
浏览
-1

首先,对不起我所说的坏名称 .

这是我刚问的问题:

Display files contain inside a particular directory by using C++ in LINUX

这是我所指的来源:

Reading The Contents of Directories

THREAD (C Programming)与我的输出相同 .

文件系统文件夹内容

- test.txt
- abc.txt
- item.txt
- records.txt

main.cpp中

#include <iostream>
#include <dirent.h>
using namespace std;

int main()
{
    Dir* dir = opendir("/home/user/desktop/TEST/FileSystem");
    struct dirent* entry;

    cout<<"Directory Contents: "<<endl;
    while((entry = readdir(dir)) != NULL)
    {
        cout << "%s " << entry->d_name << endl;
    }    
}

OUTPUT

Directory Contents:

%s ..
%s item.txt
%s test.txt
%s records.txt
%s .
%s abc.txt

我的主要问题是为什么它会在OUTPUT上显示".."和"." . 为什么它会存在,是否有任何特殊意义/目的?如何摆脱它,只在文件夹中显示文件 ONLY

提前感谢你们回答我的问题 . 我希望你们不介意我问很多问题 .

1 回答

  • 0

    在Unix和Windows中,所有目录始终包含两个条目 "." (目录本身)和 ".." 它是父级(或者本身,在极少数情况下它没有父级) . 在Unix下,通常的惯例是名称以 '.' 开头的目录是"hidden",并且不会显示,但这取决于显示程序;当你读一个目录时,你仍然可以看到它们 . 如果你想遵循这个约定,你需要一个简单的循环 if

    dirent* entry = readdir( dir );
    while ( entry != nullptr ) {
        if ( entry->d_name[0] != '.' ) {
            std::cout << entry->d_name << std::endl;
        }
        entry = readdir( dir );
    }
    

相关问题