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);

     

  • 相关阅读:
    ZZNU 正约数之和 2094
    ZZNUOJ 2022 摩斯密码
    POJ
    NYOJ 1277Decimal integer conversion (第九届河南省省赛)
    hrbust 2080链表 【贪心】
    hdu-5707-Combine String
    POJ 2442-Sequence(优先队列)
    Reversion Count
    python 07篇 内置函数和匿名函数
    python 06篇 常用模块
  • 原文地址:https://www.cnblogs.com/King-Penguin/p/5257109.html
Copyright © 2011-2022 走看看