[英]How do you read a file of strings into a linked list? (C)
我的結構定義如下:
typedef struct node {
char * word;
int wordLength;
int level;
struct node * parent;
struct node * next;
}Node;
我正在嘗試創建上述結構的鏈表,其中“ word”是一個字符串,是從文件中讀取的。 下面是我用來創建列表的函數。 似乎工作正常,並打印出單詞,但是,當我嘗試在main()
中將其打印出來時,它什么也不會打印。
void GetWords(char * dictionary, Node * Word, Node * Start)
{
FILE *fp;
char * currentWord = (char *)malloc(sizeof(char));
fp = fopen(dictionary, "r");
ErrorCheckFile(fp);
if(fscanf(fp, "%s", currentWord) == 1){
Start = Word = AllocateWords(currentWord);
}
while((fscanf(fp, "%s", currentWord)) != EOF){
Word->next = AllocateWords(currentWord);
Word = Word->next;
printf("%s: %d\n", Word->word, Word->wordLength);
}
fclose(fp);
}
我需要返回列表的開頭嗎? 如果是這樣,我該怎么做? 在此功能中,我有“開始”指向文件中的第一個單詞,我需要嗎? 我正在嘗試打印它們,只是為了確定文件已正確存儲在列表中。
我的main()函數是:
int main(int argc, char ** argv)
{
Node * Word = (Node *)malloc(sizeof(Node));
Node * Start = (Node *)malloc(sizeof(Node));
GetWords(argv[1], Word, &Start);
printf("Start: %s\n", Start->word);
printf("Word: %s\n", Word->word);
while(Word->next != NULL){
printf("%s\n", Word->word);
}
return 0;
}
打印語句僅在其中以檢查列表是否正在打印。 就目前而言,Start-> word正在打印出文件中的最后一個單詞,而Word-> word正在打印(空),而while循環根本沒有執行。
我的AllocateWords()函數如下:
Node * AllocateWords(char * string)
{
Node * p;
p = (Node *)malloc(sizeof(Node));
if(p == NULL){
fprintf(stderr, "ERROR: Cannot allocate space...\n\n");
exit(1);
}
p->word = string;
p->wordLength = strlen(p->word);
p->parent = NULL;
p->next = NULL;
return p;
}
對於Start
指針,請使用按引用調用而不是按值調用。
主功能:
Node * Start
GetWords(..., &Start)
和
void GetWords(char * dictionary, Node * Word, Node ** Start)
{
....
*Start = Word = AllocateWords(currentWord);
....
您還需要修復currentWord
的大小。 如果最大字長為255個字符,請使用:
char * currentWord = (char *)malloc(256*sizeof(char));
...
if(fscanf(fp, "%255s", currentWord) == 1){
...
while((fscanf(fp, "%255s", currentWord)) != EOF){
您還需要修復main()函數。 您不需要分配當前的單詞指針Word
或Start
節點指針。
...
Node * Word = (Node *) NULL;
Node * Start = (Node *) NULL;
GetWords(argv[1], Word, &Start);
printf("Start: %s\n", Start->word);
Word = Start;
while(Word->next){ // identical to while(World->next!=NULL){
Word=Word->next;
printf("%s\n", Word->word);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.