歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> C/C++讀取文件名(Ubuntu)

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

日期:2017/3/3 12:56:46   编辑:Linux技術
最近,在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。
Copyright © Linux教程網 All Rights Reserved