- /*
- path:被打开文件的(相对或绝对)路径
- flag:指定打开文件的方式
- O_RDONLY 只读模式
- O_WRONLY 只写模式
- O_RDWR 读写模式
- O_APPEND 每次写操作都写入文件的末尾
- O_CREAT 如果指定文件不存在,则创建这个文件
- O_EXCL 如果要创建的文件已存在,则返回 -1,并且修改 errno 的值
- O_TRUNC 如果文件存在,并且以只写/读写方式打开,则清空文件全部内容
- O_NOCTTY 如果路径名指向终端设备,不要把这个设备用作控制终端。
- O_NONBLOCK 如果路径名指向 FIFO/块文件/字符文件,则把文件的打开和后继I/O设置为非阻塞模式(nonblocking mode)。
- //以下用于同步输入输出
- O_DSYNC 等待物理 I/O 结束后再 write。在不影响读取新写入的数据的前提下,不等待文件属性更新。
- O_RSYNC read 等待所有写入同一区域的写操作完成后再进行
- O_SYNC 等待物理 I/O 结束后再 write,包括更新文件属性的 I/O
- mode:
-
- */
- fd = open(path,flag,mode)
-
- /* Move FD's file position to OFFSET bytes from the
- beginning of the file (if WHENCE is SEEK_SET),
- the current position (if WHENCE is SEEK_CUR),
- or the end of the file (if WHENCE is SEEK_END).
- Return the new file position. */
- extern __off_t lseek (int __fd, __off_t __offset, int __whence) __THROW;
-
-
- /*================================================================
- * Copyright (C) 2022 baichao All rights reserved.
- *
- * 文件名称:file_oper.cpp
- * 创 建 者:baichao
- * 创建日期:2022年06月17日
- * 描 述:
- *
- ================================================================*/
-
- #include <iostream>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <stdlib.h>
-
- int main()
- {
- char *c = (char *)malloc(5);
- int fd = open("data.txt", O_RDWR | O_CREAT | O_TRUNC, 0600);//使用O_CREAT一定要加第三个权限参数(eg:660)
- int w_size = write(fd, "01234567890123456789", 20);
- if (w_size == -1 || w_size != 20)
- {
- std::cout << "write file failed." << std::endl;
- }
- int newOffset = lseek(fd, 9, SEEK_SET);
- int r_size = read(fd, c, 5);
- if (r_size == -1 || r_size != 5)
- {
- std::cout << "read file failed." << std::endl;
- }
- std::cout << c << std::endl;
- close(fd);
- return 0;
- }
运行结果:
![]()