我正在尝试读取文本文件并将其中的字符串逐字添加到链接列表中。我是 C 的新手,不太了解指针。我遇到了一些不同的错误,只是弄乱了它,但现在我的插入方法出现了分段错误。这实际上非常令人沮丧。有人可以解释一下我在这里做错了什么吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct listNode { /* self-referential structure */
char data[50];
struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
void insert(LISTNODEPTR *, char[]);
void printList(LISTNODEPTR);
char fpeek(FILE *);
main() {
FILE *fptr;
char file_name[20];
int nrchar = 0;
LISTNODEPTR startPtr = (struct listNode *) malloc(sizeof(struct listNode));
char word[50];
char c;
int i;
printf("What is the name of the file in which the text is stored?\n");
scanf("%s",file_name);
// printf("Type the number of characters per line");
//scanf("%d", &nrchar);
fptr = fopen(file_name,"r");
while(fpeek(fptr) != EOF) {
i = 0;
while(fpeek(fptr) != ' '){
word[i] = fgetc(fptr);
i++;
printf("%d", i);
}
word[strlen(word)] = '\0';
insert(&startPtr, word);
word[0] = '\0';
}
fclose(fptr);
printList(startPtr);
return 0;
}
/* Insert a new value into the list in sorted order */
void insert(LISTNODEPTR *sPtr, char value[])
{
LISTNODEPTR newPtr, currentPtr;
newPtr = malloc(sizeof(LISTNODE));
strcpy(newPtr->data, value);
newPtr->nextPtr = NULL;
currentPtr = *sPtr;
while(currentPtr != NULL){
currentPtr = currentPtr->nextPtr;
}
currentPtr->nextPtr = newPtr;
}
/* Return 1 if the list is empty, 0 otherwise */
int isEmpty(LISTNODEPTR sPtr)
{
return sPtr == NULL;
}
/* Print the list */
void printList(LISTNODEPTR currentPtr)
{
if (currentPtr == NULL)
printf("List is empty.\n\n");
else {
printf("The list is:\n");
while (currentPtr != NULL) {
printf("%s --> ", currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
printf("EOF\n\n");
}
}
char fpeek(FILE *stream) {
char c;
c = fgetc(stream);
ungetc(c, stream);
return c;
}