最近需要用C操作文件,但是使用fopen和fseek的時候,在32位操作系統(tǒng)中,沒辦法操作2G以上的文件,后面經(jīng)過多次Google和高手指點之后通過open64、lseek解決這個問題:
1 #include <stdio.h>
2 // #define _LARGEFILE_SOURCE
3 // #define _LARGEFILE64_SOURCE
4 // #define _FILE_OFFSET_BITS 64
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8 #include <stdio.h>
9 #include <fcntl.h>
10 #include <errno.h>
11
12 int main(int argc, char *argv[])
13 {
14 off_t file_last_pos;
15 off_t end = 0;
16 // FILE *fp;
17 int fp = open64(argv[1], O_RDONLY);
18 if (fp < 0 ) {
19 printf("can't open file [%s]\n", strerror(errno));
20 return 1;
21 } else {
22 printf("file open success\n");
23 }
24 file_last_pos = lseek(fp, 0, SEEK_END);
25 printf("Size: %1d \n",file_last_pos);
26 close(fp);
27 return 0;
28 }
//這行GCC參數(shù)很重要,原來是希望通過define的方式來解決的,但是最后還是只能通過這種方式
gcc -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 test.c -o test