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

时间:2014-09-05 10:55:18

标签: c++ linux

我正在为我的大学工作。我有一个关于如何显示特定目录中包含的所有文件的问题。我的工作环境在LINUX UBUNTU 14.04 G ++编译器上。

我们举个例子,我想显示/输出这个DIRECTORY中的所有文件

/home/user/Desktop/TEST/FileSystem

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

我不确定是否可以通过使用:

来完成

- 使用Execute System Command,调用标准库头。

#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

如何对源代码进行编码,以便能够实现我期望的OUTPUT / Display。我通过Google搜索来浏览一些互联网资源。但我发现很难理解它。这就是为什么我决定在这里发布我的问题。

提前感谢你们帮我解决编码问题。

2 个答案:

答案 0 :(得分:1)

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

添加 #include 以使用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

答案 1 :(得分:0)

功能

system("ls")

只是触发命令,但你错过了命令 ls 的输出。 你需要抓住它。 在this other thread中,它解释了如何做到这一点。