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

背景:

    有一張16GB SD卡,插入開發板SD卡插槽,通過二進制方式向裏面寫入數據,在通過lseek()函數定位時返回-1,(本意是通過lseek()獲取SD卡大小)代碼如下:

large_sd.c

  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()溢出所致,修改代碼如下:

  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 型。


發佈了101 篇原創文章 · 獲贊 84 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章