一、文件描述符
文件描述符是一个较小的正整数,代表记录表的一项,通过文件描述符和一组基于文件描述符的文件操作函数完成读、写、创建、删除等操作。
相关函数有:open(打开)、creat(创建)、close(关闭)、read(读取)、write(写入)、ftruncate(重设文件大小)、lseek(重定位)、fsync、fstat、fchmod、flock、fcntl、dup(复制文件描述符)、dup2、select(I/O多路复用)、ioctl。
先介绍几个比较常用到的函数:
int open(const char *pathname, int flags); //打开文件
int open(const char *pathname, int flags, mode_t mode); //创造文件
int creat(const char *pathname, mode_t mode); //创建文件
int close(int fd);//关闭文件
ssize_t read(int fd, void *buf, size_t count);//读文件内容
ssize_t write(int fd, const void *buf, size_t count);//向文件中写入
int ftruncate(int fd, off_t length);//重设文件大小
off_t lseek(int fd, off_t offset, int whence);//定位
int dup(int oldfd);//复制文件描述符
int dup2(int oldfd, int newfd);//复制文件描述符
int fstat(int fd, struct stat *statbuf);//获取文件信息
创造文件时,mode有以下几种选项:
O_RDONLY //只读
O_WRONLY //只写
O_RDWR //可读可写
whence:
SEEK_SET
// The file offset is set to offset bytes.
SEEK_CUR
// The file offset is set to its current location plus offset bytes.
SEEK_END
// The file offset is set to the size of the file plus offset bytes.
读取文件信息:
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 */
}
二、函数的应用
1.打开文件,读取文件中内容并重新写入新内容
1 #include <func.h>
2
3 int main(int argc,char* argv[])
4 {
5 ARGS_CHECK(argc,2);
/*以读写方式打开文件*/
6 int fd=open(argv[1],O_RDWR);
/*读取文件内容并打印*/
7 char buf[128]={
0};
8 read(fd,buf,sizeof(buf));
9 printf("buf=%s\n",buf);
/*接着读取文件内容*/
10 bzero(buf,sizeof(buf));
11