Abhilash Muthuraj
Abhilash Muthuraj

Reputation: 2028

how to seek to the end of file to determine the file size?

I'm trying to get file size in c programming using seek. I can't use fseek, stat.size nor ftell, there's a custom operating system UNIX in which I need to run.

How can I find out filesize just by using seek? Is it possible?

  FILE *fd = open(argv[1], "r");

  if(fd == NULL)
  {
    printf("Not able to open the file : %s\n", argv[1]);
    return;
  }

  // Set the pointer to the end
  seek(fd, 0, SEEK_END);

Upvotes: 4

Views: 29025

Answers (3)

alk
alk

Reputation: 70981

If you are just wondering whether the construct using offset = 0 with whence = SEEK_END would position the file offset to the end of the file, then "yes" you are right, at least for the "standard f/lseek()"s I came across.

lseek() should directly return the file offset. For fseek() a following ftell() will get you the file offset.

Upvotes: 4

Brian McFarland
Brian McFarland

Reputation: 9432

Normally, open() returns an int, not a FILE *. You have to check for a return value >= 0. fopen() from <stdio.h> returns a FILE *. Also, for the record, fopen() and fseek() are part of the C standard library. A UNIX open() is part of POSIX. So in general, fopen() / fseek() is more portable.

If you are really on a custom "Unix-like" environment, to where that is no longer true (i.e. you have an custom API instead of unistd.h ) then you're not going to a good answer here without providing more info. Can you tell us what OS you are really running?

Or like Luther suggested, check the return value of lseek() if you are using a normal <unistd.h>.

Upvotes: 1

Nordic Mainframe
Nordic Mainframe

Reputation: 28767

seek? You mean lseek probably. Have a look at the manual page. What does lseek return?

Upvotes: 7

Related Questions