#arrays #c #file #sorting #metadata
Вопрос:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
// This program is going to scan all files in the current directory. It will make a tree for every folder
// and the folder will have a subsection of files in the tree format. YES SORTING!
char **word;
int folder[1000];
int filecheck[1000];
int coun = 0;
int e = 0;
int f = 0;
int u = 0;
int p = 20;
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"cannot open directory: %sn", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name,amp;statbuf);
if (S_ISDIR(statbuf.st_mode)) // Check if it's a directory
{
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
{
continue;
}
word[coun] = malloc(strlen(entry->d_name) 1);
folder[e] = coun; // Mark where the folder is.
e ;
f ;
strcpy(word[coun ], entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth 1);
f--;
}
else
{
if (f == 0)
{
filecheck[u] = coun;
u ;
}
word[coun] = malloc(strlen(entry->d_name) 1);
strcpy(word[coun ], entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
word = calloc(1000, sizeof(*word));
printdir(".", 0);
printf("now, print the words in the order.n");
int c = 0;
int l = 0;
for (int i = 0; i < coun; i) // Start readjusting the array in alphabetical order.
{
if (i == folder[c]) // If i matches with a folder, then increment and skip sorting.
{
c ;
}
else // If next is a file, then start the sorting.
{
int imin = i;
for (int j = i 1; j < folder[c]; j) // Keep sorting until the folder ends.
{
char word1[1000], word2[1000];
strcpy(word1, word[j]);
strcpy(word2, word[imin]);
for(int p = 0; word1[p]; p )
{
word1[p] = tolower(word1[p]);
}
for(int p = 0; word2[p]; p )
{
word2[p] = tolower(word2[p]);
}
if (strcmp(word1, word2) < 0)
{
imin = j;
}
}
char *tmp = word[i];
word[i] = word[imin];
word[imin] = tmp;
}
}
c = 0;
l = 0;
printf(".n");
for (int i = 0; i < coun; i) // Print the array in the specified format.
{
if (i == folder[c]) // If the folder is the same, print start of the folder.
{
printf("- %sn", word[i]);
c ;
}
else if (i == filecheck[l]) // If it's a file, print the file normally.
{
printf("- %sn", word[i]);
l ;
}
else // Print the file inside the folder.
{
printf(" - %sn", word[i]);
}
}
exit(0);
}
Моя программа должна печатать текущий каталог в древовидном формате. Он проходит сортировку совершенно нормально, за исключением последней папки, которую он проверяет. По какой-то причине hw2 работает нормально, но hw1 не сортирует.
now, print the words in the order.
.
- hw2
- find.c
- ls.c
- Makefile
- tree.c
- hw1
- grep.c
- factor.c
- uniq.c
- monster.c
- sort.c
- tree.c
- tree
Я чувствую, что мне чего-то не хватает, но я не могу понять, как заставить это работать. Я пробовал разные методы, и они не сработали. Могу ли я что-нибудь сделать?
Комментарии:
1.
printdir()
на самом деле ничего не печатает и ни для чего не используетсяdepth
.2. Я думаю, проблема в том, что
folder[c]
после последней папки нет. Таким образом, внутренний циклfor (int j = i 1; j < folder[c]; j)
не работает для последней папки.3. Вся эта конструкция кажется ошибочной. Вы должны переместить сортировку и печать в
printdir()
. Он должен иметь локальный массив только для этого каталога, а не помещать все в один большой массив.