tags:

views:

209

answers:

1

Would like to fopen() the latest file in a directory
(with naming scheme file1.txt, file2.txt, file3.txt, etc.)
Is there an API function in Visual Studio for this?
If not, is it a good idea to read in all the .txt file names and sort to get the one I need? Is there a better algorithm I could be pointed to?

Thanks.

+1  A: 

I'm going to assume by "latest" you mean "most recently modified file."

There is a C run time library function _fstat and _fstati64 (for large files > 4GB). The function signature for _fstat is:

int _fstat(int file_handle, struct _stat *file_info);

The _stat structure has a bit of useful information about the file, but you likely want the st_mtime member, which has the last modified time as a time_t (time in seconds since 00:00:00 UTC, January 1, 1970).

It may work to use the win32 functions FindFirstFile() and FindNextFile() to walk the directory, store the files in an array of a structure (containing the file name modified time) and then call qsort_s() on the array, sorting by time, in descending order.

I hope that helps.

Edmond Meinfelder
Thanks Edmond. My files are NOT > 4GB Is there still any advantage using fstat, if possible? If possible, I would still need to store in an array structure and sort, correct? Sounds like I should use the FindXFile route and sort.
Tommy
I can't think of any advantage that _fstat offers over the 64 bit version, except for the slightly smaller size of the stat structure, which doesn't seem worth much. Yes, you'll need to store and sort the values in an array. If you are using C++, you could opt an STL vector, which would be easier.
Edmond Meinfelder
Ok. Having some issues with FindNextFile: http://stackoverflow.com/questions/1336426/findfirstfile-and-findnextfile-question
Tommy