c - 尝试按文件和文件夹分隔 struct stat 时,为什么我有两个相同的数组?
问题描述
我需要输出文件,按创建日期和文件夹排序。我直接将当前目录中的所有内容分成两个数组(一个用于文件,一个用于文件),然后对它们进行处理,但突然我意识到我有两个 SIMILAR 数组。我需要帮助。
#define _DEFAULT_SOURCE ;
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void insertionSort(struct stat* myArray)
{
for(int i = 0; i < sizeof(myArray)/sizeof(struct stat); ++i)
{
int j = i - 1;
while (j >= 0 && myArray[j].st_ctime > myArray[i].st_ctime)
{
myArray[j + 1].st_ctime = myArray[j].st_ctime;
j = j - 1;
}
myArray[j + 1].st_ctime = myArray[i].st_ctime;
}
}
int main()
{
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
{
struct dirent *pDirent;
DIR *pDir;
pDir = opendir(cwd);
if(pDir != NULL)
{
struct stat sb;
struct stat* fileArray;
struct stat* folderArray;
fileArray = malloc(sizeof(struct stat));
folderArray = malloc(sizeof(struct stat));
int fiIndex = 0, foIndex = 0;
while ((pDirent = readdir(pDir)) != NULL)
{
if(strcmp(pDirent->d_name, ".") != 0
&& strcmp(pDirent->d_name, "..") != 0)
{
stat(pDirent->d_name,&sb);
//I suppose that the mistake is somewhere in this switch but I'm not really so sure
switch (sb.st_mode & S_IFMT)
{
case S_IFDIR:
folderArray[foIndex++] = sb;
folderArray = realloc(folderArray, sizeof(folderArray)+sizeof(struct stat));
break;
case S_IFREG:
fileArray[fiIndex++] = sb;
folderArray = realloc(fileArray, sizeof(fileArray)+sizeof(struct stat));
break;
}
}
}
insertionSort(fileArray);
insertionSort(folderArray);
for(int i = 0; i<sizeof(fileArray)/sizeof(stat); ++i)
{
rewinddir(pDir);
while ((pDirent = readdir(pDir)) != NULL)
{
if(strcmp(pDirent->d_name, ".") != 0
&& strcmp(pDirent->d_name, "..") != 0)
{
stat(pDirent->d_name,&sb);
if(sb.st_ino == fileArray[i].st_ino)
{
printf("%s\n",pDirent->d_name);
}
}
}
}
}
closedir(pDir);
}
return 0;
}
而且我还有一些问题,比如我应该使用 switch 吗?有没有更优雅的方式来比较文件或文件夹?打印也是一样,我觉得我让它有点难看:/
解决方案
folderArray = realloc(fileArray, ...
这肯定不是你想要的。
推荐阅读
- azure-functions - 如何获取 Azure Function App 的静态 IP 以将其列入白名单
- javascript - 我们如何使用安全标志来保护 cookie?
- react-native - 无法打印console.log in button react-native
- c# - 缺少属性时如何强制 System.Text.Json 序列化程序抛出异常?
- python - 从给定的 Valley_list 中查找键的索引
- javascript - 使用 React 的动态 CSS 动画变量
- embedded - 如何对 PA15 PE15 引脚闪烁 LED 的门控 EFM32LG230 进行时钟控制
- javascript - 如何使用 Script Lab 使用 Microsoft Office JavaScript API 进行本地文件 I/O?
- regex - 正则表达式中“and”的重复
- excel - 根据用户输入生成行数