#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;
}