C++显示目录内容问题

C++ displaying directory content issue

本文关键字:问题 显示 C++      更新时间:2023-10-16

首先,很抱歉我命名的标题不正确。

这就是我刚才问的问题:

在LINUX 中使用C++显示特定目录中包含的文件

这就是我所指的来源:

阅读目录的内容

这个THREAD(C编程)和我的输出一样。

文件系统文件夹内容

- 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;
    }    
}

输出

Directory Contents:
%s ..
%s item.txt
%s test.txt
%s records.txt
%s .
%s abc.txt

我的主要问题是为什么它会在OUTPUT上显示".."answers"."。为什么它会在那里,有什么特殊的意义/目的吗?我如何摆脱这种情况,只在文件夹中显示ONLY文件?

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

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

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