zoukankan      html  css  js  c++  java
  • Linux C 文件与目录4 将缓冲区数据写入磁盘

    将缓冲区数据写入磁盘

      所谓缓冲区,是Linux系统对文件的一种处理方式。在对文件进行写操作时,并没有立即把数据写入到磁盘,而是把数据写入到缓冲区。如果需要把数据立即写入到磁盘,可以使用sync函数。用这个函数强制写入缓冲区数据的的好处是保证数据同步


     

     

      函数原型:

        int sync(void);

    这个函数会对当前程序打开的所有文件进行处理,将缓冲区的内容写入到文件。函数没有参数,返回值为0。这个函数一般不会产生错误。

      头文件:

      #include(unistd.h)

    用法:

    fd = open(path , O_WRONLY|O_CREAT|O_TRUNC , 0766);
    if(fd != -1)
    {
    printf("opened file %s . " , path);
    }
    else
    {
    printf("can't open file %s. " , path);
    printf("errno: %d " , errno);
    printf("ERR : %s " , strerror(errno));
    }
    write(fd , s , sizeof(s));

    sync();                               //将缓冲区的数据写入磁盘

    printf("sync function done. ");
    close(fd);


    fsync

    函数fsync的作用是将缓冲区的数据写入到磁盘。与sync不同的是,这个函数可以指定打开文件的编号,执行以后会返回一个值。

    函数原型:

    int fsync(int fd);

      头文件:

      #include(unistd.h)

    返回值:如果函数执行成功则返回0,否则返回-1。

    fd = open(path , O_WRONLY|O_CREAT|O_TRUNC , 0766);
    if(fd != -1)
    {
      printf("opened file %s . " , path);
    }
    else
    {
      printf("can't open file %s. " , path);
      printf("errno: %d " , errno);
      printf("ERR : %s " , strerror(errno));
    }
      write(fd , s , sizeof(s));

      if(fsync(fd) == 0)

      {

        printf("fsync function done. ");

      }

      else

      {

        printf("fsync function failed. ");

      }
    close(fd);

     

  • 相关阅读:
    CSS cursor 属性笔记
    sql 不等于 <>
    去掉时间中的时分秒
    ref 和 out区别
    关于闭包(未完待续)
    面向对象——多态(摘)
    SQL Service 数据库 基本操作 视图 触发器 游标 存储过程
    遍历winform 页面上所有的textbox控价并赋值string.Empty
    关于Html 和Xml 区别(备忘)
    python之面向对象进阶
  • 原文地址:https://www.cnblogs.com/King-Penguin/p/5257109.html
Copyright © 2011-2022 走看看