Re: How to lseek the larger file > 2GB under linux

Michal Nazarewicz <[email protected]>
Newsgroups org.kernel.vger.linux-c-programming
Message-ID <[email protected]>
Nicle <[email protected]> writes:
> I have a file > 2GB, and my job is seeking the file to pos: 2.1G.
> But, it seems that the lseek64 doesn't work.

> #define _LARGEFILE64_SOURCE
> #include ...
>
> int main() {
>  int fd = -1;
>  long long pos = (long long) 2*1024*1024*1024 + 10; // over 2G

A long shot, but try (2LL << 30) (the "LL" is important).  I don't
expect that will make it work but if you're out of ideas... ;)

>  fd = open(FILENAME, O_WRONLY|O_LARGEFILE);
>  if (fd < 0) { /* ... */ }
>
>  if (lseek64(fd, pos, SEEK_SET) < 0)
>      fprintf(stderr, "Failed seeking to %lld, %s\n", pos, strerror(errno));
>
>  return 0;
> }

>  Then the building cmd:   gcc -o test test.c -D_FILE_OFFSET_BITS=64
>  Output:            >     Failed seeking to 2147483658, Success.
>
> The return val of lseek64  was "<0", but the strerror told me "Success".

BTW. The following works fine for me:

#v+
#define _LARGEFILE64_SOURCE

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define RUN(expr) if ((expr) < 0) { perror(#expr); return 1; } else (void)0

int main(void) {
	const long long pos = (2LL << 30) + 10;
	int fd;

	RUN(fd = open("deleteme", O_WRONLY | O_LARGEFILE | O_CREAT, 0600));
	RUN(lseek64(fd, pos, SEEK_SET));
	RUN(write(fd, "a", 1));
	return 0;
}
#v-

-- 
Best regards,                                         _     _
 .o. | Liege of Serenly Enlightened Majesty of      o' \,=./ `o
 ..o | Computer Science,  Michal "mina86" Nazarewicz   (o o)
 ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo--
signature.asc (application/pgp-signature, 197 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.11 (GNU/Linux)

iEYEARECAAYFAkoQOVEACgkQUyzLALfG3x6MPQCfb7y475fsN6yRK/2rvx0v2UnK
AQ4An3TNj65zcu7k8xThPnfKkzUSUF10
=8iXr
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.