Thursday, July 30, 2009

How do I get the size of a file I opened in C?

I have opened a file (with fopen() ), so, normally, I have a pointer to a file structure. The problem is, I need to know the size of the file I opened. I thought it might be somwere in the structure, the file descriptor, perhaps. But, I have no idea what FILE structure looks like, or what members it has. So, what would be the easiest way for me to find out the size of the file I just opened?





I'm writting in C.


Thank you in advance.

How do I get the size of a file I opened in C?
Hi there!





The system call to use is fstat().





fstat takes two parameters: a pointer to a file structure, and a "stat" structure. You create the "stat" struct, and pass that into fstat too. Then fstat fills it out. Your file size is in "st_size" in the structure.





If you're using Mac OS X or Linux (or another such OS), you can enter "man fstat" at the command line to learn more. Or check your programming documentation. Or check the link I've posted below.





I could give you some code, but I think that should be enough to go on with. Good luck!





Edit: Ugh, sorry, I'm silly. fstat takes a "file descriptor". You turn a "FILE *" into a file descriptor with the fileno() call. Make your call: fstat(fileno(file_in), %26amp;FileInfo)
Reply:// open the file


FILE * pFile = fopen("c:\\temp\\test2.txt", "rb");





// seek to the end


fseek(pFile, 0, SEEK_END);





// the current file position tells us how big this file is


int fileSize = ftell(pFile);





// seek back to the beginning so we can start reading it in


fseek(pFile, 0, SEEK_SET);





Calroth's answer of using fstat is correct when using handles returned by open()/close(), but I don't think it works with FILE *.
Reply:I don't think there is a function to determine the size of a file.


What u can do is, when u have the FILE struct is to get the end position of the last character, which is also the file size!





long lSize;


FILE * pFile;





// open the file


pFile =fopen("somefilename.ext", "r");





fseek (pFile , 0 , SEEK_END); // move the read pointer to end of the file


lSize = ftell (pFile); // get the file position == file size


rewind (pFile); // move back to the front of the file








U might get in trouble if ur file is extremely large.


Then the function ftell will produce the wrong value. (compiler depend)


Maybe u can use


int fgetpos ( FILE * stream, fpos_t * position );
Reply:There is a function to return the file length.


Under Turbo C++ (DOS version) and Borland C++


filelength(fileno(ifp));


Visual C++


_filelength(fileno(fp));


Recommend that fp is in Binary Mode


No comments:

Post a Comment