背景:
有一張16GB SD卡,插入開發板SD卡插槽,通過二進制方式向裏面寫入數據,在通過lseek()函數定位時返回-1,(本意是通過lseek()獲取SD卡大小)代碼如下:
large_sd.c
- #include <sys/types.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- int main(int argc, char *argv[])
- {
- long max_seek = 0;
- int fd = open("/dev/mmcblk0",O_RDWR);
- if(fd < 0)
- {
- printf("open file error.\n");
- return -1;
- }
- max_seek = lseek(fd,0,SEEK_END);
- printf("MAX SEEK = %ld\n",max_seek);
- return 0;
- }
在開發板上執行,打印結果:
MAX SEEK = -1
後來通過搜索發現,原來是lseek()溢出所致,修改代碼如下:
- #include <sys/types.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- int main(int argc, char *argv[])
- {
- long long max_seek = 0;
- int fd = open("/dev/mmcblk0",O_RDWR);
- if(fd < 0)
- {
- printf("open file error.\n");
- return -1;
- }
- max_seek = lseek(fd,0,SEEK_END);
- printf("MAX SEEK = %lld\n",max_seek);
- return 0;
- }
編譯: 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 型。