zoukankan      html  css  js  c++  java
  • 使用无缓冲IO函数读写文件

    前言

      本文介绍使用无缓冲IO函数进行文件读写。

      所谓的无缓冲是指该IO函数通过调用系统调用实现,其实系统调用内部的读写实现也是使用了缓冲技术的。

    读写步骤

      1. 打开文件  open 函数

      2. 读写文件  read write 函数

      3. ( 如果需要 )修改文件指针  lseek 函数  ( 可能和 2 交替进行 )

      4. 关闭文件  close 函数

    代码示例

     1 //
     2 // 本程序往一个文件中写入一个整型数组
     3 // 然后读取这个数组并输出
     4 //
     5 
     6 #include <unistd.h>
     7 #include <fcntl.h>
     8 #include <errno.h>
     9 #include <iostream>
    10 #include <string>
    11 
    12 using namespace std;
    13 
    14 const int LEN=5;
    15 
    16 int main(void) {
    17     string filename; 
    18     cout << "请输入要处理的文件名: ";
    19     cin >> filename;
    20 
    21     // 打开 filename 文件。
    22     // 注意:
    23     //    1. 第一个参数必须转换成C的字符串格式
    24     //    2. 如果找不到文件,就会以 777 权限创建一个新的文件。
    25     //    3. 如果要进行读写,还要使用O_RDWR参数。
    26     int fd = 0;
    27     if (!(fd = open(filename.c_str(), O_CREAT|O_EXCL|O_RDWR, 777))) {
    28         cout << "打开/创建文件失败" << endl;
    29         return 1;
    30     }
    31 
    32     // 初始化测试数组
    33     int buf[LEN];
    34     for (int i=0; i<LEN; i++) {
    35         buf[i] = i;
    36     }
    37 
    38     // 将数组中的数据写入到打开的文件中
    39     if (write(fd, buf, LEN*sizeof(int)) != LEN*sizeof(int)) {
    40         cout << "写入失败" << endl;
    41         return 2;
    42     }
    43 
    44     // 写入指针回退两个位置
    45     lseek(fd, -2*sizeof(int), SEEK_CUR);
    46 
    47     // 继续写入数据 
    48     if (write(fd, buf, LEN*sizeof(int)) != LEN*sizeof(int)) {
    49         cout << "写入失败" << endl;
    50         return 2;
    51     }
    52 
    53     // 写入指针回到文件顶部
    54     lseek(fd, 0, SEEK_SET);
    55 
    56     // 从文件中读取数据并输出到标准输出
    57     int n=0;
    58     while ((n = read(fd, buf, LEN*sizeof(int))) > 0) {
    59         // 这里切记不能够直接用write输出到标准输入,因为write不知道数组里面放的数据是什么类型。
    60         for (int i=0; i<n/sizeof(int); i++) {
    61             cout << buf[i] << " ";
    62         }
    63         cout << endl;
    64     }
    65     if (n<0) {
    66         cout << "读入失败" << endl;
    67         return 3;
    68     }
    69 
    70     // 关闭文件
    71     close(fd);
    72 
    73     return 0;
    74 }

    小结

      1. read 和 write 函数是以二进制的方式读/写,函数本身是不会去识别数据格式的。

      2. 当程序语句比较长的时候,要注意算符的优先级。( 参考代码 58 行 )

      3. 使用完文件之后记得关闭文件描述符

  • 相关阅读:
    MongoDB:数据库管理
    MongoDB:用户管理
    MongoDB:入门
    彻底透析SpringBoot jar可执行原理
    轻松了解Spring中的控制反转和依赖注入(一)
    领域驱动最佳实践--用代码来告诉你来如何进行领域驱动设计
    血的教训--如何正确使用线程池submit和execute方法
    领域驱动设计之实战权限系统微服务
    为什么我们需要领域驱动设计
    【Go入门学习】golang自定义路由控制实现(二)-流式注册接口以及支持RESTFUL
  • 原文地址:https://www.cnblogs.com/scut-fm/p/3643907.html
Copyright © 2011-2022 走看看