【发布时间】:2017-02-14 05:31:05
【问题描述】:
我一直在尝试创建一个链表数组。该数组的大小为 26,每个部分对应于字母表中的一个字母。用户输入 PC 的目录,然后该目录中的任何文件夹或文件的名称将根据它们的开头字母添加到数组中的链表中。
我是怎么做到的->
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
我的节点及其声明:
struct node{
char data[50];
struct node *next;
};
struct node* nodeArray[26];
我的字母表:
const char* basis[26] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
一个字符串比较函数,用于检查我的单词在数组中的哪个链表(与字母表比较)
int StartsWith(const char *a, const char *b)
{
if(strncasecmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
我在哪里添加节点以及问题出在哪里(printf("1") 是为了阻止我的计算机基本上崩溃):
void addNode(struct node **q,const char *d){
if(((*q)->data)==NULL){
*q = malloc(sizeof(struct node));
strncpy((*q)->data,d,50);
(*q)->next = NULL;
} else {
(*q)->next = malloc(sizeof(struct node));
*q = (*q)->next;
printf("1");
addNode(q,d);
}
}
调用addNode的函数,directory是已经检查存在的计算机目录:
void returner(char* directory){
int i;
DIR *dp;
struct dirent *ep;
char* tempD;
dp = opendir (directory);
struct node **z;
while ((ep = readdir(dp))){
tempD = (char*)malloc(50);
if ( !strcmp(ep->d_name, ".") || !strcmp(ep->d_name, "..") ){
} else {
strncpy(tempD, ep->d_name, 50);
for(i=0; i<26 ; i++){
if(StartsWith(tempD, basis[i])){
z = &nodeArray[i];
addNode(z,tempD);
print();
}
}
}
free(tempD);
}
closedir (dp);
}
打印功能:
void print(){
int i;
struct node *temp;
for(i=0 ; i < 26; i++){
temp = malloc(sizeof(struct node));
temp = nodeArray[i];
while(temp != NULL){
printf("%s\n",temp->data);
temp = temp->next;
}
}
}
将第一个节点添加到数组上的某个点时,程序看起来很好,例如“aaa.txt”“bbb.txt”“ccc.txt”“ddd.txt”,但是尝试添加第二个节点就像“ccc.txt”之后的“ccd.txt”一样,当它永远运行或直到电脑崩溃时,它就存在
【问题讨论】:
标签: c arrays linked-list dirent.h