我正在做一项作业,要求我创建一个类似于 ls 的函数。 我的代码工作正常,但是当涉及到实现
的行为时ls -l child //where child is a folder
有一个奇怪的行为。
假设我位于“parent”文件夹中,其中有一个子文件夹“child”,其中包含一些文本文件。当我从父文件夹运行程序时,它会找到该文件夹并打印出其中文本文件的属性。但是,只有当父文件夹中存在相同的文件时,它才会打印子文件夹中的文件。
这是我正在使用的代码片段
char CurrDir[100];
DIR *pDir = NULL;
struct dirent *pFileNames = NULL;
getcwd(CurrDir, sizeof(CurrDir))
strncat(CurrDir, "/", strlen(CurrDir));
unsigned int CurrDirLen = strlen(CurrDir);
unsigned int CombSize = CurrDirLen + strlen(argv[1]);
char SuperCharArr[CombSize];
for(int i = 0; i < CombSize; ++i)
{
if( i < strlen(CurrDir) )
SuperCharArr[i] = CurrDir[i];
else
SuperCharArr[i] = argv[1][i%CurrDirLen];
}//for
//insert null character at the end of the character
SuperCharArr[CombSize] = '\0';
pDir = opendir( SuperCharArr );
printf("%s\n", SuperCharArr);
if( pDir != NULL )
{
//Directory detected as pDir is a DirectoryStream
printf("%s\n", "pDir not null");
PrintHeader();
while( (pFileNames = readdir(pDir)) != NULL )
{
PrintFileDeails(pFileNames);
}
}//if
最佳答案
在我在这里发布的原始代码中,有一个名为 PrintFileDeails(pFileNames) 的函数,它接受直接类型的参数。
在PrintFileDeails()中,有一个检查文件状态的函数,代码如下,
struct stat FileStat;
if( stat(pFileNames->d_name, &FileStat) == -1 )
{
perror("stat");
exit(EXIT_FAILURE);
}//if
这行代码会打印出一个错误,他们找不到该文件,并且 AAT 的注释让我再次检查我的代码,因为我怀疑它没有读取正确的文件夹。因此,在我传递了应该从中读取文件的完整路径之后,它工作得很好。因此,代码改为这样。
if( stat(pFullPath, &FileStat) == -1 )
{
perror("stat");
exit(EXIT_FAILURE);
}//if
其中 pFullPath 传递了 SuperCharArr 的变量,其中包含要搜索的文件所在的完整路径。
stat() 的手册页也有帮助,可以找到 here
关于c - 从文件夹中检索文件的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26463179/