如何从目录中获取最新的文件
这是特定于创建日志文件的。当我使用应用程序连接到服务器时,它将详细信息写入日志文件。当日志文件达到特定大小(假设为 1MB)时,我将创建另一个名为 LOG2.log 的文件。
现在,在写回日志文件时,有两个甚至更多日志文件,我想选取最新的一个。我不想遍历该目录中的所有文件并拾取文件,因为这将花费处理时间,是否有其他方法来获取目录中最后创建的文件或日志文件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最好的选择是轮换日志文件,这是 Unix 中通常完成的操作(通常通过 cron)。
一种可能的实现是保留 10 个(或任意多个)旧日志文件,如果您的程序检测到 Log.log 已结束1MB,然后将Log09.log移动到Log10.log,Log08.log移动到Log09.log,7到8,6到7,...2到3,然后Log.log到Log02.log。最后,创建一个新的Log.log文件并继续记录。
这样,您将始终写入 Log.log,并且文件系统不再神秘。理论上,这种方法可以扩展到数量惊人的日志文件(超出您合理需要的数量),并且比写入 Log3023.log 更标准。另外,人们总是知道在哪里可以找到当前日志。
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.
我相信答案是“僵硬”。您必须自己迭代并找到最新的一个,因为操作系统不会为每个可能的排序顺序保留索引,以防万一有人需要它们。
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.
可以修改服务器吗?如果是这样,也许引入一个 LASTLOG.log 文件,其中包含最新日志文件的名称或其实际内容。
否则,托尼是对的。除了迭代自己之外,没有真正的方法可以做到这一点。
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.
优雅的怎么样:
How about the elegant :
最有效的方法是使用专门的函数来遍历所有条目(因为 NTFS 或 FAT 不按时间索引),但忽略不需要的内容。为此,请使用信息级别
FindExInfoBasic
调用FindFirstFileEx
。这会跳过 8.3 名称解析。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 levelFindExInfoBasic
. This skips 8.3 name resolution.