LINUX下寫大文件 -D _FILE_OFFSET_BITS=64或者open時加O_LARGEFILE

http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201141211197621/

在32位機器下,默認情況下,文件長度是off_t類型,這個可以從ftrucate的參數,從stat獲取的文件屬性struct stat中都可以看出文件的長度是用off_t類型表示的,即文件的長度在32位機器下默認是long int類型。

       所以,默認情況下,在Linux系統下,fopen和open操作的文件大小不能超過2G

       我們製造了一個異常文件,5G左右,可以使用dd命令來構建,也可以寫個腳本來構建。

       我寫了一段程序來測試:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
 FILE *fp;
 int fd;

 fp = fopen("./bill_test","a+");                                                              //bill_test是一個5G左右的文件
 if(fp == NULL)
 {
  perror("fopen bill_test fail::");
 }
 else
 {
  int ret = 0;
  ret = fprintf(fp,"%s\t","bill"); 

  if(ret < 0)
  {
   perror("write bill_test fail::");
   fclose(fp);
   exit(1);
  }
  fclose(fp);
 }

 fd = open("./bill_test",O_APPEND|O_RDWR,0666);                  //bill_test是一個5G左右的文件
 if(fd == -1)
 {
  perror("open bill_test fail::");
 }
 else
 {
  int len=0;
  len = write(fd,"hello",5);
  if(len == -1)
  {
   perror("write bill_test fail::");
   close(fd);
   exit(1);
  }
  close(fd);
 }
 return 0;
}

//當使用: g++ file_test.cpp -o file_test           對源碼編譯後,運行結果如下:

./file_test 
fopen bill_test fail::: File too large                       
open bill_test fail::: File too large

 

可以看出,在32位機器下,不能直接支持超過2G的文件。

 

解決方案一、

              g++   -D _FILE_OFFSET_BITS=64   file_test.cpp  -o   file_test

此時在用tail  -f    bill_test,然後再運行./file_test,可以看到數據被正常的寫入bill_test文件中。

 

解決方案二、

             對與open,可以使用O_LARGEFILE參數,即:

             fd   =   open("./bill_test",O_LARGEFILE|O_APPEND|O_RDWR,0666);

             然後就沒用問題了,但是fopen沒有這個參數,只能按照方法一來解決。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章