问题:在centos5.5 32位系统上,开发的c++程序,用vfprintf 输出日志文件,发现当日志大于2G时会报错“File size limit exceeded”。开始以为ulimit问题,查看发现没有限制。

        经过网上查找资料得到这样结论:在32位机器下,默认情况下,文件长度是off_t类型,这个可以从ftrucate的参数,从stat获取的文件属性struct stat中都可以看出文件的长度是用off_t类型表示的,即文件的长度在32位机器下默认是long int类型。所以,默认情况下,在Linux系统下,fopen和open操作的文件大小不能超过2G。

自己测试:程序如下

 

#include <stdio.h>
#include <stdarg.h>
void WriteFormatted (FILE * stream, const char * format, ...)
{
va_list args;
va_start (args, format);
vfprintf (stream, format, args);
va_end (args);
}
int main ()
{
FILE * pFile;
int i;
pFile = fopen ("myfile.txt","w");
for(i=0;i<100000000;i++)
{
WriteFormatted (pFile,"Call with %d variable argument.\n",1);
WriteFormatted (pFile,"Call with %d variable %s.\n",2,"arguments");
}
fclose (pFile);
return 0;
}

   编译执行时

[root@localhost c]# g++ writefile.cpp -o writefile
 [root@localhost c]# ./writefile 
 File size limit exceeded

当时文件为:-rw-r--r-- 1 root root 2.0G Jun 20 22:09 myfile.txt

解决办法:

一、定义宏 
// 定义宏,使得可以处理大文件(>2GB) 
#undef _FILE_OFFSET_BITS 
#define _FILE_OFFSET_BITS 64 
#include <unistd.h> 
#include <dirent.h>
二、在makefile编译选项里加上-D_FILE_OFFSET_BITS=64 -D_LARGE_FILE
三、使用fopen64函数
用的第二种已经写到5G了
[root@localhost c]# g++ -D_FILE_OFFSET_BITS=64  writefile.cpp -o writefile
[root@localhost c]# ./writefile 
[root@localhost c]# ll -h myfile.txt 
-rw-r--r-- 1 root root 5.9G Jun 20 22:41 myfile.txt