项目中要计算指定文件夹的大小。
百度查到这篇文章,https://my.oschina.net/Tsybius2014/blog/330628
方法可行,运行正确。
拿到我们的项目中,却遇到一些问题:程序中一些读文件的代码,开始报异常,都不到文件。这些都是以前没有遇到过的问题。
到底是什么情况呢?排查了好久,终于发现使用该文章提供的计算文件夹大小的函数(暂且叫做GetDirectorySize),其中有改变当前目录的代码:
chdir(dir);
我们的项目是多线程的,一个线程调用GetDirectorySize,调用的过程中改变了当前目录,而此时另一个线程使用相对路径去读文件,原来能读到的,现在就读不到了。特别提示chdir改变的是,当前进程(当然包括其下所有线程)的工作目录!!!(具体可以查看线程共享进程的那些资源?)
为了去掉GetDirectorySize的副作用,我重新实现了该函数:
1 #include <stdio.h>
2 #include <sys/stat.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <dirent.h>
7 #include <string.h>
8
9 //计算某目录所占空间大小(包含本身的4096Byte)
10 long long int GetDirectorySize(char *dir)
11 {
12 DIR *dp;
13 struct dirent *entry;
14 struct stat statbuf;
15 long long int totalSize=0;
16
17 if ((dp = opendir(dir)) == NULL)
18 {
19 fprintf(stderr, "Cannot open dir: %s\n", dir);
20 return -1; //可能是个文件,或者目录不存在
21 }
22
23 //先加上自身目录的大小
24 lstat(dir, &statbuf);
25 totalSize+=statbuf.st_size;
26
27 while ((entry = readdir(dp)) != NULL)
28 {
29 char subdir[256];
30 sprintf(subdir, "%s/%s", dir, entry->d_name);
31 lstat(subdir, &statbuf);
32
33 if (S_ISDIR(statbuf.st_mode))
34 {
35 if (strcmp(".", entry->d_name) == 0 ||
36 strcmp("..", entry->d_name) == 0)
37 {
38 continue;
39 }
40
41 long long int subDirSize = GetDirectorySize(subdir);
42 totalSize+=subDirSize;
43 }
44 else
45 {
46 totalSize+=statbuf.st_size;
47 }
48 }
49
50 closedir(dp);
51 return totalSize;
52 }
53
54 int main(int argc, char* argv[])
55 {
56 char* dir = argv[1];
57 long long int totalSize = GetDirectorySize(dir);
58 printf("totalSize: %lld\n", totalSize);
59
60 return 0;
61 }
原文链接: https://www.cnblogs.com/emituofo/p/6225403.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/246535
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!