c - 使用 nftw 时如何避免使用全局变量

标签 c global-variables nftw

我想用nftw在C中遍历一个目录结构。

但是,考虑到我想做的事情,我看不到使用全局变量的方法。

使用 (n)ftw 的教科书示例都涉及执行诸如打印文件名之类的操作。相反,我想获取路径名和文件校验和并将它们放入数据结构中。但考虑到可以传递给 nftw 的内容的限制,我看不到这样做的好方法。

我使用的解决方案涉及一个全局变量。然后,nftw 调用的函数可以访问该变量并添加所需的数据。

有什么合理的方法可以不使用全局变量来做到这一点吗?

Here's the exchange in previous post on stackoverflow in which someone suggested I post this as a follow-up.

最佳答案

使用 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/

相关文章:

C - 长时间运行的 while 循环出现段错误

javascript - 在 jquery.live() 中声明可在所有函数中使用的 var

global-variables - 在 Inno Setup Scripting (Pascal) 中,如何设置全局变量的初始值?

c - nftw 传递具有未定义值的 tflag

linux - 如何使用ftw删除目录内容

c - 为什么会出现段错误?我正在使用 stat、mmap、nftw 和 memcmp 等

c - 如何最大限度地提高此 C 代码的性能?

c - 将函数中的静态变量初始化为非常量值

c++ - 有没有办法删除 C 宏中的引号?

javascript - 在 NodeJS 中使用和更新全局变量安全吗?