2

This is specific to creating a logfiles. When I am connecting to a server using my application, it writes the details to a log file. When the log file reaches to specific size let's say 1MB then I create another file named LOG2.log.

Now While Writing back to log file , there are two or even more log files and I want to pick up the latest one. I don not want to traverse through all the files in that directory and the pick up the file, as this will take processing time, Is there any other way to get the last created file or log file in the directory.

roalz
  • 2,699
  • 3
  • 25
  • 42
Simsons
  • 12,295
  • 42
  • 153
  • 269

5 Answers5

3

Your best bet is to rotate log files, which is what gets done in Unix normally (generally via cron.)

One possible implementation is to keep 10 (or however many) old log files around, if your program detects that Log.log is over 1MB then move Log09.log to Log10.log, Log08.log to Log09.log, 7 to 8, 6 to 7, ... 2 to 3, and then Log.log to Log02.log. Finally, create a new Log.log file and continue recording.

This way you'll always write to Log.log and there's no filesystem mystery. In theory, this approach is scalable to ridiculous numbers of log files (more than you would ever reasonably need) and is more standard than writing to Log3023.log. Plus, one would always know where to find the current log.

OmnipotentEntity
  • 16,531
  • 6
  • 62
  • 96
1

I believe the answer is "stiff". You have to iterate and find the most recent one yourself, as the OS won't keep indices for each possible sort order around on the off chance someone may want them.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
0

Are you able to modify the server? If so, perhaps introduce a LASTLOG.log file that either contains the name of the latest log file, or the actual contents of it.

Otherwise, Tony's right.. No real way to do it other than iterate through yourself.

Demian Brecht
  • 21,135
  • 5
  • 42
  • 46
0

How about the elegant :

ls -t | head -n 1
Spyros
  • 46,820
  • 25
  • 86
  • 129
0

The most efficient way is to use a specialized function to go through all entries (as NTFS or FAT don't index by time), but ignore what you don't need. For that, call FindFirstFileEx with info level FindExInfoBasic. This skips 8.3 name resolution.

MSalters
  • 173,980
  • 10
  • 155
  • 350