write: file too large,linux 通过lseek定位大文件

背景:

    有一张16GB SD卡,插入开发板SD卡插槽,通过二进制方式向里面写入数据,在通过lseek()函数定位时返回-1,(本意是通过lseek()获取SD卡大小)代码如下:

large_sd.c

[cpp]  view plain  copy
  1. #include <sys/types.h>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <string.h>  
  5. #include <unistd.h>  
  6. #include <fcntl.h>  
  7.   
  8. int main(int argc, char *argv[])  
  9. {  
  10.   
  11.     long max_seek = 0;  
  12.   
  13.     int fd = open("/dev/mmcblk0",O_RDWR);  
  14.     if(fd < 0)  
  15.     {  
  16.       printf("open file error.\n");    
  17.       return -1;  
  18.     }  
  19.     max_seek = lseek(fd,0,SEEK_END);  
  20.   
  21.     printf("MAX SEEK = %ld\n",max_seek);  
  22.     return 0;  
  23. }  


编译: arm-linux-gcc -o large_sd large_sd.c

在开发板上执行,打印结果:

MAX SEEK = -1


后来通过搜索发现,原来是lseek()溢出所致,修改代码如下:

[cpp]  view plain  copy
  1. #include <sys/types.h>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <string.h>  
  5. #include <unistd.h>  
  6. #include <fcntl.h>  
  7.   
  8. int main(int argc, char *argv[])  
  9. {  
  10.   
  11.    long long max_seek = 0;  
  12.   
  13.     int fd = open("/dev/mmcblk0",O_RDWR);  
  14.     if(fd < 0)  
  15.     {  
  16.         printf("open file error.\n");  
  17.         return -1;  
  18.     }  
  19.     max_seek = lseek(fd,0,SEEK_END);  
  20.   
  21.     printf("MAX SEEK = %lld\n",max_seek);  
  22.     return 0;  
  23. }  

编译: arm-linux-gcc  -D_FILE_OFFSET_BITS=64  -o large_sd large_sd.c

再次在开发板上执行:

MAX SEEK = 15707668480

成功。


总结:

1.如果通过lseek()定位大文件,返回值需要使用long long型变量接收,以防止溢出。

2.编译时要加选项-D_FILE_OFFSET_BITS=64来定义_FILE_OFFSET_BITS为64

3.printf使用%lld来打印long long int 型。


猜你喜欢

转载自blog.csdn.net/hpu11/article/details/79852715