【发布时间】:2012-01-10 22:16:27
【问题描述】:
我有一个小问题,我必须完成一个练习。我们必须实现一个递归的“ls”程序,它打印出“n”个最大的文件。但是也有一些问题。
1)
我有三个文件,main.c、list.c 和 list.h。在 list.h 中,我包含了 string.h、stdio.h、stdlib.h,声明了一个结构(char* 文件名、long long 文件大小和结构元素* next)和两个方法(append、printlist)。在 list.c 中,我包含了 list.h 并实现了 append 和 printlist 这两种方法。在 main.c 中,我包含了 unistd.h、dirent.h、sys/stat.h 和 list.h。
当我尝试使用“gcc main.c”编译它时,我收到错误“使用未声明的方法追加和打印列表”,但如果我使用的是 Eclipse,它构建得很好。我该如何解决这个问题?
确切的错误
/tmp/ccLbHnqR.o: In function `main':
main.c:(.text+0x189): undefined reference to `printliste'
/tmp/ccLbHnqR.o: In function `ftop':
main.c:(.text+0x1f6): undefined reference to `append'
2)
为了实现我尝试使用自排序列表的功能,即遍历列表直到最后一个大于新值的值,然后将新值的指针设置为最后一个值的指针,然后最后一个值的指针是新值。
理论上它应该有效,但实际上它不是。
追加方法如下所示
void append(struct element **lst, char* filename, long long filesize){
struct element *newElement;
struct element *lst_iter = *lst;
newElement = malloc(sizeof(*newElement)); // create new element
newElement->filename = filename;
newElement->filesize = filesize;
newElement->next = NULL; // important to find the end of the list
if ( lst_iter != NULL ) { // if elements are existing
//if our element is bigger than the first element
if(lst_iter->filesize < newElement->filesize){
newElement->next = lst_iter;
*lst = newElement;
} else {
while(lst_iter->next != NULL){
if(lst_iter->filesize > newElement->filesize) lst_iter = lst_iter->next;
else break;
}
newElement->next = lst_iter->next;
lst_iter->next = newElement;
}
}
else // if the list is empty our value is the new value
*lst=newElement;
}
我正在使用我的“ftop”方法中的这个方法,它获取一个目录,将此目录中的每个文件添加到列表中,并且对于每个目录它再次调用“ftop”。
void ftop(char* path){
DIR *dir;
struct dirent *ent;
//open the directory
dir = opendir(path);
if (dir != NULL) {
//for each file/directory in it
while ((ent = readdir(dir)) != NULL) {
struct stat st;
//if it is a file, append it to the list
if(S_ISREG(st.st_mode)){
append(&list, ent->d_name, st.st_size);
} else {
//if it is a directory, use recursion
ftop(ent->d_name);
}
}
}
}
但我不明白为什么它不起作用。我知道你不想做别人的功课,但我会感谢你给我的每一个提示。
P.s.:如果你想要完整的代码
【问题讨论】:
-
我敢打赌我知道这个作业是从哪里来的 ;)
-
请将单独的问题作为单独的问题发布。
标签: c list filesystems header-files