我正在做一个任务,需要我创建一个类似于ls的函数。 我的代码工作正常,但是当涉及到实施的从文件夹中检索文件的属性
ls -l child //where child is a folder
的行为有一个怪异的行为。
比方说,我在文件夹“父”,并在其中我有一个子文件夹,'孩子',其中包含一些文本文件。当我从父文件夹运行我的程序时,它会找到该文件夹并打印出文本文件的属性。但是,只有当父文件夹中存在相同的文件时,它才会打印子文件夹中的文件。
下面是我使用的代码片段,
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
'READDIR()'但我想它返回只有文件__name__,而不是全部__path__。换句话说,您需要先使用SuperCharArr路径名限定'pFileNames-> d_name',然后才能使用它。 – AAT 2014-10-20 10:32:05
@AAT是的,但是在每个循环中它都会返回文件名,它是您正在读取的目录中的每个文件的属性,在这种情况下由pDir指针表示。不过,谢谢你的建议。 – winhung 2014-10-22 06:12:54
等等,你的评论让我检查了一些东西,我认为你是对的。它正在检查错误的路径。至少,在我的函数PrintFileDeails()中,它是。谢谢,我很快就会发布正确答案。 – winhung 2014-10-22 06:39:10