我想用nftw在C中遍历一个目录结构。
但是,考虑到我想做的事情,我看不到使用全局变量的方法。
使用 (n)ftw 的教科书示例都涉及执行诸如打印文件名之类的操作。相反,我想获取路径名和文件校验和并将它们放入数据结构中。但考虑到可以传递给 nftw 的内容的限制,我看不到这样做的好方法。
我使用的解决方案涉及一个全局变量。然后,nftw 调用的函数可以访问该变量并添加所需的数据。
有什么合理的方法可以不使用全局变量来做到这一点吗?
最佳答案
使用 ftw 可能真的非常不好。在内部它会保存你使用的函数指针,如果另一个线程做了其他事情它会覆盖函数指针。
Horror scenario:
thread 1: count billions of files thread 2: delete some files thread 1: ---oops, it is now deleting billions of files instead of counting them.
简而言之。你最好使用 fts_open。
如果您仍想使用 nftw,那么我的建议是将“全局”类型放入命名空间并将其标记为“thread_local”。您应该能够根据自己的需要进行调整。
/* in some cpp file */
namespace {
thread_local size_t gTotalBytes{0}; // thread local makes this thread safe
int GetSize(const char* path, const struct stat* statPtr, int currentFlag, struct FTW* internalFtwUsage) {
gTotalBytes+= statPtr->st_size;
return 0; //ntfw continues
}
} // namespace
size_t RecursiveFolderDiskUsed(const std::string& startPath) {
const int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS;
const int maxFileDescriptorsToUse = 1024; // or whatever
const int result = nftw(startPath.c_str(), GetSize, maxFileDescriptorsToUse , flags);
// log or something if result== -1
return gTotalBytes;
}
关于c - 使用 nftw 时如何避免使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10281198/