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

转自:https://blog.csdn.net/lsq2902101015/article/details/51373911

最近,在Ubuntu系统上需要使用C来获取指定文件夹下的文件名,发现不同使用windows系统上的方法。

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

windows系统方法点这里


一、代码


先给出代码,如下:


 
 
  1. //头文件
  2. #include <iostream>
  3. #include <sys/types.h>
  4. #include <dirent.h>
  5. #include <vector>
  6. #include <string.h>
  7. using namespace std;
  8. void GetFileNames(string path,vector<string>& filenames)
  9. {
  10. DIR *pDir;
  11. struct dirent* ptr;
  12. if(!(pDir = opendir(path.c_str())))
  13. return;
  14. while((ptr = readdir(pDir))!= 0) {
  15. if ( strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
  16. filenames.push_back(path + "/" + ptr->d_name);
  17. }
  18. closedir(pDir);
  19. }
  20. int main() {
  21. vector< string> file_name;
  22. string path = "/home/image";
  23. GetFileNames(path, file_name);
  24. for( int i = 0; i <file_name.size(); i++)
  25. {
  26. cout<<file_name[i]<< endl;
  27. }
  28. return 0;
  29. }

二、解析


获取文件名的基本流程为打开文件夹、读取文件名和关闭文件夹,分别使用函数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>头文件中,用来保存文件信息,定义如下:



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


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


 
 
  1. enum
  2. {
  3. DT_UNKNOWN = 0,
  4. # define DT_UNKNOWN DT_UNKNOWN
  5. DT_FIFO = 1,
  6. # define DT_FIFO DT_FIFO
  7. DT_CHR = 2,
  8. # define DT_CHR DT_CHR
  9. DT_DIR = 4,
  10. # define DT_DIR DT_DIR
  11. DT_BLK = 6,
  12. # define DT_BLK DT_BLK
  13. DT_REG = 8,
  14. # define DT_REG DT_REG
  15. DT_LNK = 10,
  16. # define DT_LNK DT_LNK
  17. DT_SOCK = 12,
  18. # define DT_SOCK DT_SOCK
  19. DT_WHT = 14
  20. # define DT_WHT DT_WHT
  21. };

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

int closedir(DIR *pDir); 
 
 

pDir为调用opendir()的返回值,成功关闭返回0,否则返回-1。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值