1.open
头文件:
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
参数:
pathname:文件绝对路径/文件名
flags:O_RDONLY(读), O_WRONLY(写), or O_RDWR(可读可写).
mode_t mode :权限
返回值:
非负,未占用的最小正整数
2.read
头文件:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数:
fd:文件描述符
3.write
用法:
size_t write(int fd, const void *buf, size_t count);
参数:
fd:文件描述符
*buf:缓冲区地址
count :写入字节数
4.lseek文件定位
头文件:
#include<unistd.h>
用法:
off_t lseek(int fd, off_t offset, int whence);
参数:
fd:文件描述符
offset:偏移量
whence:当前位置基点
5.关闭文件
int close(int fd);
目录操作
1.打开目录
#include <dirent.h>
//打开一个已经存在的目录
DIR *opendir(const char *name);
返回值:
成功返回目录流指针,失败返回-1;
2.读目录
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
返回值:
成功返回目录信息结构体,失败返回NULL
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /* Not an offset; see below */
unsigned short d_reclen; /* Length of this record */
unsigned char d_type; /* Type of file; not supported
by all filesystem types */
char d_name[256]; /* Null-terminated filename */
};
3.查看文件属性
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//返回值On success, zero is returned. On error, -1 is returned
int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* Inode number */
mode_t st_mode; /* File type and mode */
nlink_t st_nlink; /* Number of hard links */
uid_t st_uid; /* User ID of owner */
gid_t st_gid; /* Group ID of owner */
dev_t st_rdev; /* Device ID (if special file) */
off_t st_size; /* Total size, in bytes */
blksize_t st_blksize; /* Block size for filesystem I/O */
blkcnt_t st_blocks; /* Number of 512B blocks allocated */
struct timespec st_atim; /* Time of last access */
struct timespec st_mtim; /* Time of last modification */
struct timespec st_ctim; /* Time of last status change */
#define st_atime st_atim.tv_sec /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};
判断文件是何类型:
// File type and mode 高位代表文件类型,低位代表文件权限
mode_t st_mode;
S_IFMT 0170000 bit mask for the file type bit field
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
Thus, to test for a regular file (for example), one could write:
stat(pathname, &sb);
if ((sb.st_mode & S_IFMT) == S_IFREG) {
/* Handle regular file */
}