获取文件信息

#include <sys/stat.h>
struct stat {  
        _dev_t     st_dev;        //文件所在磁盘驱动器号  
        _ino_t     st_ino;        //inode,FAT、NTFS文件系统无意义  
        unsigned short st_mode;   //文件、文件夹的标志  
        short      st_nlink;      //非NTFS系统上通常为1  
        short      st_uid;        //UNIX系统上为userid,windows上为0  
        short      st_gid;        //UNIX系统上为groupid,windows上为0  
        _dev_t     st_rdev;       //驱动器号,与st_dev相同  
        _off_t     st_size;       //文件字节数  
        time_t st_atime;          //上次访问时间  
        time_t st_mtime;          //上次修改时间  
        time_t st_ctime;          //创建时间  
        };


函数声明

int _stat(  
   const char *path,  
   struct _stat *buffer   
); 

注意:win32(_stat)  linux(stat)

参数:

path——文件或者文件夹的路径

buffer——获取的信息保存在内存中

返回值:

正确——返回0

错误——返回-1,具体错误码保存在errno

st_mode

以下数值
 - S_IFMT mask bit
 - S_IFDIR directory
 - S_IFCHR character special
 - S_IFREG normal file
 - S_IFBLK block special
 - S_IFFIFO fifo
 - S_IFSOCK socket

例子:

#include <iostream>
#include <sys/stat.h>
using namespace std;


int main(int argc, const char * argv[]) {
    struct stat buf;
    int x = lstat("/Users/TLG/Downloads/somethings",&buf);
    if(x == 0)
    {
        if(S_ISDIR(buf.st_mode))
        {
            cout << "dir." << endl;
        }
        else if( S_ISREG(buf.st_mode))
        {
            cout << "file." << endl;
        }
        else
        {
            cout << "nothing." << endl;
        }
    }
    else
    {
        cout << "path error." << endl;
    }
    return 0;
}

遍历文件夹
enum eStats
{
    eSuccessful,
    eFail
};


int getFileName(const char *path)
{
    DIR *basedir = NULL;
    basedir = opendir(path);
    if(NULL == basedir)
    {
        cout << "can not open directory:" << path << endl;
        return eFail;
    }
    
    chdir(path);
    struct dirent *entry;
    struct stat    filest;
    cout << " file list :" << endl;
    while((entry = readdir(basedir)) != NULL)
    {
        lstat(entry->d_name,&filest);
        if(S_ISDIR(filest.st_mode))
        {
            if(strcmp(".",entry->d_name) == 0 ||
               strcmp("..",entry->d_name) == 0)
                continue;
            char tmp[255] = {0};
            sprintf(tmp, "%s/%s",path,entry->d_name);
            getFileName(tmp);
        }
        else
        {
            cout <<  entry->d_name << endl;
        }
    }
    return eSuccessful;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值