Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to find length of a file? 1

Status
Not open for further replies.

Flappy

Programmer
Jul 30, 2002
35
0
0
AU
Is it possible to find the length of a file before I read it? so i can just malloc the memory and read the file into it?
 
Yes, it is possible, what OS and compiler are you using, and are you opening the file as a stream (fopen) or handle/file descriptor using open?

Look at the stat and fstat functions.

Alternatively, on an open file you can do:

for a stream:
Code:
FILE *fi = fopen("filename","r");
fseek(fi,0,SEEK_END);
length = tell(fi);
rewind(fi);

Also, some compilers had a filelength function for file descriptors.

Good luck.

for a file descriptor:
Code:
int handle=open("filename"...);
length = lseek(handle,O,SEEK_END);
lseek(handle,0,SEEK_SET);

Good luck.
 
Thanks that should do the trick - I'm using stream so I'll use your first example there. I'm using Linux but will eventually port it over to Win32.

 
On Linux (or UNIX) try:

#include <sys/stat.h>

main()
{
struct stat buf;

if (stat("filename",&buf) != -1)
printf("Size: %d\n",buf.st_size);
else
printf("---ERROR---\n");

}

The stat call returns information about the given file into the structure "buf". On of the fields in this structure is the file size.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top