2014-09-05 20 views
0

我正在为我的大学进行作业。我有一个关于如何显示特定目录内包含的所有文件的问题。我的工作环境是LINUX UBUNTU 14.04 G ++编译器。通过在LINUX中使用C++在特定目录中包含显示文件

让我们举个例子,我想显示/输出全部在这个目录里的文件

/home/user/Desktop/TEST/FileSystem 

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

我不知道是否可以做到使用:

- 使用执行系统命令,通过调用标准库头。

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

输出我的预期:

/FileSystem Folder contains: 

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

我如何可以编写我的源代码,使我能够实现这个输出/显示我的预期。我通过使用Google搜索来浏览一些互联网来源。但是我发现理解它有困难。这就是为什么我决定在这里发布我的问题。

非常感谢您提前帮助我解决我的编码问题。

+1

阅读[Boost Filesystem library](http://www.boost.org/doc/libs/1_56_0/libs/filesystem/doc/index.htm)。 – 2014-09-05 10:57:30

+0

指出,谢谢。 :) @JoachimPileborg – J4X 2014-09-05 11:01:35

+0

Boost文件系统或Qt与它的QDir类。 当你午餐system()命令时,你应该以某种方式捕获输出。看看这个线程http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c – madduci 2014-09-05 11:23:26

回答

1

您需要先打开需要列出文件的目录,然后才需要读取目录。

Add #include for 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 

请参阅此线程http://www.cpp-home.com/tutorials/107_6.htm

+0

感谢@Rahul提供代码片段和链接。我试图在我的程序上实现,它可以完美地作为我想要的预期输出。 – J4X 2014-09-05 11:22:05

+0

欢迎...... :) – 2014-09-05 11:24:58

0

功能

system("ls") 

只是射击命令,但你缺少的命令的输出LS是什么。 你需要捕捉它。 在this other thread它解释了如何做到这一点。

相关问题