0

I'm working on assignment for my university. I have a question on how to display all the files contain inside a particular directory. My working environment is on LINUX UBUNTU 14.04 G++ Compiler.

Let's take an example, I want to display/output all the files inside this DIRECTORY

/home/user/Desktop/TEST/FileSystem

File contains inside FOLDER FileSystem
-test.txt
-abc.txt
-item.txt
-records.txt

I'm not sure whether it can be done by using:

-Using Execute System Command, by calling standard library header.

#include <iostream>
#include <stdlib.h>
int main()
{
    system("pwd");  // Directory: /home/user/Desktop/TEST/FileSystem
    system("ls");   // Display every files contain in the FileSystem Folder 
}

OUTPUT that I expected:

/FileSystem Folder contains:

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

How can I code my source code so that I'm able to achieving this OUTPUT/Display that I expected. I have go through some internet sources by googling it. But I find out difficulty on understand it. That's why I have made a decision to post my question on here.

Thank You in advance to you guys for helping me to solve my coding problem.

J4X
  • 119
  • 14
  • 1
    Read about [the Boost Filesystem library](http://www.boost.org/doc/libs/1_56_0/libs/filesystem/doc/index.htm). – Some programmer dude Sep 05 '14 at 10:57
  • Boost Filesystem or Qt with its QDir class. When you lunch the system() command, you should somehow capture the output. Look at this thread http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c – madduci Sep 05 '14 at 11:23
  • @blackibiza wow, this is another great solution. I'll try to implement it. Thank You :) – J4X Sep 05 '14 at 11:32
  • @J4X no problem. This might reduce the requirement of external libs. – madduci Sep 05 '14 at 11:33

2 Answers2

1

You need to first open directory for which you need to list files after that you need to read directory.

Add #include for using apis.

#include <dirent.h>

/* open the directory "/home/" for reading. */ 
DIR* dir = opendir("/home/users");

entry = readdir(dir)); //files or directories in /home 

//Add logic to verify entry is file or directory

Refer this thread http://www.cpp-home.com/tutorials/107_6.htm

Rahul R Dhobi
  • 5,668
  • 1
  • 29
  • 38
  • Thank You @Rahul for providing the snippets of the code and also the link. I've tried to implement on my program and it works perfectly as the expected output that I want. – J4X Sep 05 '14 at 11:22
0

the function

system("ls")

is just firing the command but you are missing what the output of the command ls is. You need to capture it. In this other thread it's explained how to do it.

Community
  • 1
  • 1
madduci
  • 2,635
  • 1
  • 32
  • 51