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 .\n" , path);

}

else

{

printf("can't open file %s.\n" , path);

printf("errno: %d\n" , errno);

printf("ERR : %s\n" , strerror(errno));

}

write(fd , s , sizeof(s));

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

printf("sync function done.\n");

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 .\n" , path);

}

else

{

  printf("can't open file %s.\n" , path);

  printf("errno: %d\n" , errno);

  printf("ERR : %s\n" , strerror(errno));

}

  write(fd , s , sizeof(s));

  if(fsync(fd) == 0)

  {

    printf("fsync function done.\n");

  }

  else

  {

    printf("fsync function failed.\n");

  }

close(fd);