基于文件描述符的文件I/O - xuwenshg's Blog
基于文件描述符的文件I/O
xuwenshg
posted @ 2012年3月12日 23:59
in C
, 1287 阅读
1、相关函数说明
(1)open()
所需头文件:#include <sys/types.h>、<sys/stat.h>、<fcntl.h>
函数原型:int open(const char *pathname, int flags, int perms)
作用:用于打开或创建文件,同时可以设置文件属性及用户权限
(2)close()
所需头文件:#include <unistd.h>
函数原型:int close(int fd)
作用:用于关闭一个被打开的文件read()
(3)read()
所需头文件:#include <unistd.h>
函数原型:ssize_t read(int fd, void *buff, size_t count)
作用:从指定的文件描述符中读取数据到缓冲区中,并返回读取的字节数
(4)write()
所需头文件:#include <unistd.h>
函数原型:ssize_t write(int fd, void *buff, size_t count)
作用:向已打开的文件中写数据,从文件描述符的当前指针开始写
(5)lseek()
所需头文件:#include <sys/types.h>
函数原型:off_t lseek(int fd, off_t offset, int whence)
作用:在指定文件描述符中将当前指针定位到相应位置
2、示例代码
/* copy_file.c */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #define BUFFER_SIZE 1024 /* 每次读写缓存大小,影响运行效率*/ #define SRC_FILE_NAME "src_file" /* 源文件名 */ #define DEST_FILE_NAME "dest_file" /* 目标文件名文件名 */ #define OFFSET 10240 /* 拷贝的数据大小 */ int main() { int src_file, dest_file; unsigned char buff[BUFFER_SIZE]; int real_read_len; /* 以只读方式打开源文件 */ src_file = open(SRC_FILE_NAME, O_RDONLY); /* 以只写方式打开目标文件,若此文件不存在则创建, 访问权限值为644 */ dest_file = open(DEST_FILE_NAME, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (src_file < 0 || dest_file < 0) { printf("Open file error\n"); exit(1); } /* 将源文件的读写指针移到最后10KB的起始位置*/ lseek(src_file, -OFFSET, SEEK_END); /* 读取源文件的最后10KB数据并写到目标文件中,每次读写1KB */ while ((real_read_len = read(src_file, buff, sizeof(buff))) > 0) { write(dest_file, buff, real_read_len); } close(dest_file); close(src_file); return 0; }