• linux:文件操作(open、write/read、lseek、close)


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

    运行结果:

  • 相关阅读:
    聊聊设计模式——状态模式
    PostMan使用,访问路径@RequestMapping
    MFC 常用控件
    百分点大数据技术团队:解读ToB产品架构设计的挑战及应对方案
    Azure 机器学习 - 使用 Visual Studio Code训练图像分类 TensorFlow 模型
    写代码的七八九十宗罪,多图、胆小慎入!
    【Vue3.0移动端项目--旅游网】-- 房屋信息和房屋设施
    【docker命令】
    使用 DeepSpeed 和 Hugging Face 🤗 Transformer 微调 FLAN-T5 XL/XXL
    【牛客刷题】
  • 原文地址:https://blog.csdn.net/weixin_40179091/article/details/125326027