您的位置:首页 > 编程语言 > C语言/C++

C/C++读取文件名(Ubuntu)

2016-05-11 14:29 411 查看
最近,在Ubuntu系统上需要使用C来获取指定文件夹下的文件名,发现不同使用windows系统上的方法。

本文即在Ubuntu系统上实现获取文件名的功能。

windows系统方法点这里

一、代码

先给出代码,如下:

//头文件
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <string.h>

using namespace std;

void GetFileNames(string path,vector<string>& filenames)
{
DIR *pDir;
struct dirent* ptr;
if(!(pDir = opendir(path.c_str())))
return;
while((ptr = readdir(pDir))!=0) {
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
filenames.push_back(path + "/" + ptr->d_name);
}
closedir(pDir);
}

int main() {
vector<string> file_name;
string path = "/home/image";

GetFileNames(path, file_name);

for(int i = 0; i <file_name.size(); i++)
{
cout<<file_name[i]<<endl;
}

return 0;
}


二、解析

获取文件名的基本流程为打开文件夹、读取文件名和关闭文件夹,分别使用函数opendir()、readdir()以及closedir()实现。

1、头文件

所依赖的头文件分别为#include<sys/types.h>和#include<dirent.h>

2、opendir()、readdir()和closedir()

要读取文件夹下的文件名,首先需要打开目录,opendir()函数原型:

DIR *opendir(const char *pathname);


成功打开会返回DIR类型的指针,失败返回NULL。

读取文件信息,使用readdir()函数:

struct dirent *readdir(DIR *pDir);


函数返回值是dirent结构体指针,当到达目录末尾或者出错时返回NULL。

pDir为调用opendir()时返回的值。下面看以下dirent结构体。

dirent结构体被定义在了#include<dirent.h>头文件中,用来保存文件信息,定义如下:

struct dirent
{
__ino_t d_ino;   /*inode number 索引节点号*/
__off_t d_off;   /*offset to this dirent 在目录文件中的偏移*/
unsigned short int d_reclen;   /*length of this d_name 文件名长*/
unsigned char d_type;   /*the type of d_name 文件类型*/
char d_name[256];    /*file name(null-terminated) 文件名 */
};


d_name字段表示文件名。

d_type字段表示文件类型,取值定义如下:

enum
{
DT_UNKNOWN = 0,
# define DT_UNKNOWN DT_UNKNOWN
DT_FIFO = 1,
# define DT_FIFO DT_FIFO
DT_CHR = 2,
# define DT_CHR DT_CHR
DT_DIR = 4,
# define DT_DIR DT_DIR
DT_BLK = 6,
# define DT_BLK DT_BLK
DT_REG = 8,
# define DT_REG DT_REG
DT_LNK = 10,
# define DT_LNK DT_LNK
DT_SOCK = 12,
# define DT_SOCK DT_SOCK
DT_WHT = 14
# define DT_WHT DT_WHT
};


最后,使用closedir()关闭被打开的目录:

int closedir(DIR *pDir);


pDir为调用opendir()的返回值,成功关闭返回0,否则返回-1。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: