
#include
#include
#include
int stat(const char *pathname, struct stat *statbuf); //获取文件属性
struct stat {
dev_t st_dev;
ino_t st_ino;
mode_t st_mode;
nlink_t st_nlink;
uid_t st_uid;
gid_t st_gid;
dev_t st_rdev;
off_t st_size;
blksize_t st_blksize;
blkcnt_t st_blocks;
};
注:使用下面的宏函数可以判断文件的类型:参数为struct stat的st_mode成员
S_ISREG(st_mode); --- 判断是否是普通文件
S_ISDIR(st_mode) directory?
S_ISCHR(st_mode) character device?
S_ISBLK(st_mode) block device?
S_ISFIFO(st_mode) FIFO (named pipe)?
S_ISLNK(st_mode) symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(st_mode) socket? (Not in POSIX.1-1996.)
```
int system(char *commad); //执行shell命令
int chdir(char *path); //切换当前的工作路径,类似与cd命令
参数:
path: 要切换的路径
返回值:
成功: 0
失败: -1, 并设置errno
#include
#include
DIR *opendir(const char *name); //打开目录
参数:
name: 目录名
返回值:
成功:目录流指针
失败:NULL, 并设置errno
int closedir(DIR *dirp); //关闭目录
参数:
dirp: 目录流指针
struct dirent *readdir(DIR *dirp); //读取目录
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[256];
};
返回值:
读取的文件dirent结构体指针
当读取到目录流结束时,返回NULL
代码如下:
#include
#include
int main(int argc, char *argv[])
{
int ret;
struct stat buf;
if (argc < 2)
{
fprintf(stderr, "Usage: %s
return -1;
}
ret = stat(argv[1], &buf); //获取文件属性
if (ret < 0)
{
perror("stat");
return -1;
}
if (S_ISREG(buf.st_mode)) //判断文件的类型是否是普通文件
printf("%s is regular file!n", argv[1]);
else
{
printf("%s isn't a regular file!n", argv[1]);
return -1;
}
printf("size: %ldn", buf.st_size); //文件的大小
return 0;
}