-1

Firstly, Sorry for the bad title that I've named.

This is the question that I just asked:

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

This is the source that I refer to:

Reading The Contents of Directories

This THREAD (C Programming) having the same output like mine.

FileSystem Folder Contents

- 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

My main question is why it will display the ".." and "." on the OUTPUT. Why it will be there, is there any special meaning/purposes? How do I get rid of that and just display files ONLY in the folder?

Thank you in advance to you guys on answering my question. I hope you guys don't mind I ask a lot of question.

Community
  • 1
  • 1
J4X
  • 119
  • 14

1 Answers1

0

In Unix and Windows, all directories always contain the two entries "." (the directory itself) and ".." it's parent (or itself, in the rare cases where it has no parent). Under Unix, the usual convention is that directories whose name starts with a '.' are "hidden", and will not be displayed, but this is up to the displaying program; when you read a directory, you still see them. If you want to follow this convention, a simple if in your loop is all you need:

dirent* entry = readdir( dir );
while ( entry != nullptr ) {
    if ( entry->d_name[0] != '.' ) {
        std::cout << entry->d_name << std::endl;
    }
    entry = readdir( dir );
}
James Kanze
  • 150,581
  • 18
  • 184
  • 329