Mar 26, 2004 #1 Flappy Programmer Joined Jul 30, 2002 Messages 35 Location 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?
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?
Mar 26, 2004 1 #2 itsgsd Programmer Joined Sep 4, 2002 Messages 163 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. Upvote 0 Downvote
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.
Mar 26, 2004 Thread starter #3 Flappy Programmer Joined Jul 30, 2002 Messages 35 Location AU 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. Upvote 0 Downvote
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.
Mar 28, 2004 #4 dsanchez2 Programmer Joined Nov 10, 2002 Messages 79 Location AU 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. Upvote 0 Downvote
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.