linux系统调用 —— 文件管理
open
函数原型
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// 功能:打开指定的文件,并设置打开的方式。返回一个文件描述符
int open(const char *pathname, int flags);
// 功能:创建名pathname为文件时,设置文件权限mode. 并打开当前的文件,设置打开的方式.返回一个文件描述符
int open(const char *pathname, int flags, mode_t mode);
函数参数
- pathname 要打开的文件,如~/my/test.c
- flags 打开文件的方式,
- mode 文件本身具有的权限属性。 mode只有在创建文件时才使用。
flags打开文件的方式
- O_RDONLY 以只读的方式,打开已经存在的文件。
- O_RDWR 读写方式打开文件
- O_WRONLY 以只写的方式,打开文件。
- O_CREAT 创建文件
- O_EXCL 一般,打开文件的权限使用 O_CREAT 时,O_EXCL 会配合使用。用来检测文件是否存在。 如果文件存在,则报错。
- O_TRUNC 清空文件(将文件大小置为0)
- O_APPEND 以追加方式打开
close
函数原型
#include <unistd.h>
// 功能:关闭打开文件,参数fd为打开的文件描述符。关闭成功为0,失败为-1.
int close(int fd);
read/write
函数原型
#include <unistd.h>
// 功能:从fd中读取数据到buf中,count为预计读取的字节个数。读取成功返回实际读到的字节数。否则返回-1
ssize_t read(int fd, void *buf, size_t count);
// 功能:将buf中的数据写入fd中,count为预计写取的字节个数。写入成功返回实际读到的字节数。否则返回-1
ssize_t write(int fd,const void *buf, size_t count);
lseek
函数原型
#include <sys/types.h>
#include <unistd.h>
// 功能:重新定位偏移量,返回值为当前定位好的读写位置距文件开头的偏移量。off_t 为%ld
off_t lseek(int fd, off_t offset, int whence);
函数参数
- fd 文件描述符
- offset 偏移量,当为负数时为向左偏移,正数为向右偏移
- whence 基准位置。
可选的基准位置
- SEEK_SET 文件开头偏移量
- SEEK_CUR 当前的偏移量
- SEEK_END 文件末尾的偏移量
实例
lseek重定位
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
int main()
{
int fd = open("./a.c", O_RDWR|O_CREAT|O_EXCL, 0664); // 创建a.c文件,并以读写的方式打开
if (fd < 0) {
printf("Failed to create file. The file already exists\n");
return -1;
}
char buf[] = "Welcome to china";
char s1[20] = {0};
char s2[20] = {0};
int x = write(fd, buf, strlen(buf)); // 向a.c文件中写入数据
read(fd, s1, sizeof(s1)); // 从a.c文件中读取数据到s1数组中,当前的偏移量已经到文件末尾,读取不到数据
printf("s1 : %s\n", s1);
off_t off = lseek(fd, 0, SEEK_SET); // 以为SEEK_SET基准位置,重新定位到文件初始位置
read(fd, s2, sizeof(s2)); // 从a.c文件中读取数据s2数组中
printf("s2 : %s\n", s2);
printf("off: %ld\n", off);
close(fd);
return 0;
}
输出
实现简易cp拷贝功能
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <strings.h>
int main(int argc,char *argv[])
{
if(argc < 3)
{
printf("%s src dest\n",argv[0]);
return -1;
}
int fd_src = open(argv[1],O_RDONLY); // 打开将要拷贝的文件
int fd_dest = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC, 0666); // 打开将要拷贝到哪个目标文件
if(fd_src < 0 || fd_dest < 0)
{
perror("open"); // 错误输出
return -1;
}
int x;
char buf[100];
while((x = read(fd_src,buf,sizeof(buf))) != 0) { // 从源文件中读取文件到buf
write(fd_dest,buf,x); // 将buf拷贝到目标文件中
}
close(fd_src); // 关闭
close(fd_dest);
return 0;
}