【发布时间】:2011-05-04 10:55:06
【问题描述】:
有没有办法使用 c 标准库函数获取目录的大小?
【问题讨论】:
-
请说明您的意思是“该目录下所有文件的合并文件大小”或“目录中的文件数”。
-
目录列表是操作系统特定的。
有没有办法使用 c 标准库函数获取目录的大小?
【问题讨论】:
没有。 C 和 C++ 标准库不明确支持目录的概念。
就他们而言,“C:\test\test.txt”中的反斜杠没有特殊含义。这是由操作系统来处理的。
【讨论】:
“目录的大小”是什么意思?
这些都不可能通过单个 C 库或系统调用实现。
【讨论】:
查看this post with regard to how to get the size of a file。您可能需要汇总目录中文件的大小才能得到“目录大小”。
如果您使用的是 Linux,您可能会对这些帖子感兴趣:
【讨论】:
这应该能让你继续前进。
对于窗户,请参阅: http://code.google.com/p/portaputty/source/browse/trunk/windows/dirent.c?r=8
或者这个: http://www.softagalleria.net/dirent.php
或者只使用 MinGW 编译器。
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h> // for opendir(), readdir(), closedir()
#include <sys/stat.h> // for stat()
dir_proc = opendir(PROC_DIRECTORY) ;
if (dir_proc == NULL)
{
perror("Couldn't open the " PROC_DIRECTORY " directory") ;
return (pid_t) -2 ;
}
// Loop while not NULL
while ( (de_DirEntity = readdir(dir_proc)) )
{
if (de_DirEntity->d_type == DT_DIR)
{
if (IsNumeric(de_DirEntity->d_name))
{
strcpy(chrarry_CommandLinePath, PROC_DIRECTORY) ;
strcat(chrarry_CommandLinePath, de_DirEntity->d_name) ;
strcat(chrarry_CommandLinePath, "/cmdline") ;
FILE* fd_CmdLineFile = fopen (chrarry_CommandLinePath, "rt") ; // open the file for reading text
if (fd_CmdLineFile)
{
fscanf(fd_CmdLineFile, "%s", chrarry_NameOfProcess) ; // read from /proc/<NR>/cmdline
fclose(fd_CmdLineFile); // close the file prior to exiting the routine
if (strrchr(chrarry_NameOfProcess, '/'))
chrptr_StringToCompare = strrchr(chrarry_NameOfProcess, '/') +1 ;
else
chrptr_StringToCompare = chrarry_NameOfProcess ;
//printf("Process name: %s\n", chrarry_NameOfProcess);
//printf("Pure Process name: %s\n", chrptr_StringToCompare );
if ( CompareFunction(chrptr_StringToCompare, cchrptr_ProcessName, intCaseSensitiveness) )
{
pid_ProcessIdentifier = (pid_t) atoi(de_DirEntity->d_name) ;
closedir(dir_proc) ;
return pid_ProcessIdentifier ;
}
}
}
}
}
closedir(dir_proc) ;
【讨论】: