C/linux 中的排序 glob

发布于 2024-12-14 03:12:51 字数 353 浏览 2 评论 0原文

我需要在目录中找到最新创建/修改的文件。基本上就是 ls -t *.bla 的作用。在 C 中,而不是 PHP,所以这个问题对我没有帮助 - glob() - 按日期排序


这是一个不该做的示例(分叉进程)不便宜,它很懒)

char filename[100];
FILE *f = popen("ls -1t /*.blabla");
fscanf(f, "%s", filename);
pclose(f);

:?

I need to find the latest created/modified files in a directory. Basically what ls -t *.bla does. In C, not PHP, so this question does not help me -
glob() - sort by date


This is an example of what no to do (forking a process is not cheap, it's lazy):

char filename[100];
FILE *f = popen("ls -1t /*.blabla");
fscanf(f, "%s", filename);
pclose(f);

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴骨ら 2024-12-21 03:12:51

使用 opendir() 打开目录,将文件名 (readdir()) 读入数组,然后对其执行 qsort() array 及其回调使用 stat() 读取创建或修改日期,然后您反过来用它来告诉 qsort() 如何排序。不要忘记使用 Closedir() 关闭目录(按照下面 larsmans 评论中提出的修改,这可能会变得更加有效)。

最后,排序完成后,取出第一个/最后一个数组条目(取决于您的排序方式),然后就完成了。

如果可用,您也可以使用 scandir() 一次完成所有这些(尽管您将无法绕过必要时执行更多 stat() 调用,因为这些需要在 qsort 的比较回调中完成对于这个解决方案)。

PS:有人知道如何原子地做到这一点吗?

Open the directory using opendir(), read the file names (readdir()) into an array, then do a qsort() on that array with its callback using stat() to read in creation or modification dates, which you then in turn use to tell qsort() how to sort. Do not forget to close the directory using closedir() (This could pimped to be even more effcient following the modification proposed in larsmans's comment below).

Finally after sorting is done, take the first/last array entry (depending on how you have sorted) and you are done.

If available you could also just use scandir() to have all this done at once (although you will not get around doing more stat() calls then necessary, as those need to be done in qsort's compare callback for this solution).

PS: Does anybody have an idea how to do this atomically?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文