我得到了这段代码的段错误:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
typedef struct _node
{
char *buffer;
struct _node *next;
int node_count;
} node;
typedef struct _list
{
node *head;
node *tail;
} list;
list *node_list;
int list_node_lookup(list *l, char *buffer)
{
node *temp = l->head;
while(temp)
{
if (strcmp(temp->buffer, buffer) == 0)
{
/* We got it earlier */
temp->node_count++;
return 1;
}
else
{
temp = temp->next;
}
}
return 0;
}
int adding_to_list(list *l, char *buffer)
{
int ret;
char *tmp = (char *)malloc(sizeof(char)*(strlen(buffer) + 1));
node *new_node = (node *)malloc(sizeof(struct _node));
/* Empty list */
if (l->head == NULL)
{
strcpy(tmp, buffer);
new_node->buffer = tmp;
new_node->node_count = 0;
l->head = l->tail = new_node;
l->head->next = NULL;
}
else
{
/* The list is not empty */
ret = list_node_lookup(l, buffer);
if (ret == 1)
{
fprintf(stdout, "Got it before\n");
}
else
{
strcpy(tmp, buffer);
new_node->buffer = tmp;
new_node->node_count = 0;
l->tail->next = new_node;
l->tail = new_node;
new_node->next = NULL;
fprintf(stdout, "Adding this cust : %s\n", buffer);
}
}
return 0;
}
int main(int argc, char **argv)
{
FILE *cust;
char buf[BUFSIZ];
DIR* cust_dir;
struct dirent* input;
node_list = (list *) malloc(sizeof(struct _list));
if (node_list == NULL)
{
return 1;
}
node_list->head = node_list->tail = NULL;
if (NULL == (cust_dir = opendir("cust_dir")))
{
return 1;
}
while ((input = readdir(cust_dir)))
{
if (!strcmp (input->d_name, "."))
continue;
if (!strcmp (input->d_name, ".."))
continue;
cust = fopen(input->d_name, "r");
while (fgets(buf, BUFSIZ, cust) != NULL)
{
adding_to_list(node_list, buf);
}
fclose(cust);
}
return 0;
}
当我使用包含这两个文件的目录(它们包含空行)测试我的代码时,我得到了奇怪的输出和段错误。
我在同一个目录中使用了这个文件两次(customers.txt 和 customers_copy.txt):
1
2
3
4 Kristina Chung H Kristina H. Chung Chung, Kristina H.
5 Paige Chen H Paige H. Chen Chen, Paige H.
6 Sherri Melton E Sherri E. Melton Melton, Sherri E.
7 Gretchen Hill I Gretchen I. Hill Hill, Gretchen I.
8 Karen Puckett U Karen U. Puckett Puckett, Karen U.
9 Patrick Song O Patrick O. Song Song, Patrick O.
10 Elsie Hamilton A Elsie A. Hamilton Hamilton, Elsie A.
11
12 Hazel Bender E Hazel E. Bender Bender, Hazel E.
13
前三行是空的(当我使用一个文件时一切正常,但是这多个文件我得到了一个段错误)。
感谢您的帮助,以了解问题所在。