C 检查目录是否存在的更快方法
我正在使用 opendir 函数来检查目录是否存在。问题是我在一个巨大的循环中使用它,并且它正在给我的应用程序使用的内存充气。
检查 C 中目录是否存在的最佳(最快)方法是什么?如果不存在,创建它的最佳(最快)方法是什么?
I'm using opendir function to check if a directory exists. The problem is that I'm using it on a massive loop and it's inflating the ram used by my app.
What is the best (fastest) way to check if a directory exists in C? What is the best (fastest) way to create it if doesn't exists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
考虑使用
stat
。S_ISDIR(s.st_mode)
会告诉您它是否是一个目录。样本:
Consider using
stat
.S_ISDIR(s.st_mode)
will tell you if it's a directory.Sample:
您可以调用
mkdir()
。如果该目录不存在,则将创建该目录并返回0
。如果目录存在,则将返回-1
,并将errno
设置为EEXIST
。You could call
mkdir()
. If the directory does not exist then it will be created and0
will be returned. If the directory exists then-1
will be returned anderrno
will be set toEEXIST
.我更喜欢使用
access()
如果你确保尾随
/ 在目录名称中,这非常有效。
I prefer using
access()
If you ensure a trailing
/
in the directory name, this works perfectly.如果可用的话,我会使用 stat() 。
I would use
stat()
, if available.听起来你有内存泄漏。只要您记得在成功打开目录后始终调用 closedir,调用 opendir 就不应该增加应用程序的 RAM。另外,请确保释放分配用于计算目录名称的所有缓冲区。
It sounds like you have a memory leak. Calling opendir should not inflate the RAM of your app as long as you remember to always call closedir after successfully opening a directory. Also, make sure you are freeing any buffers you allocated to compute the directory name.