问题描述
我对 C 编程非常陌生,并且遇到了一些困难.我试图从一行读取一行到一个文本文件,然后将每一行添加到一个简单的链表中.我已经尝试了很多,但我还没有找到解决方案.到目前为止,在我的代码中,我能够从文件中读取,但我无法理解如何保存文本行并将其添加到链接列表中.
I'm very new to C-programming, and I'm having some difficulties. I'm trying to read line from line to a text file, and then add each line to a simple linked list. I have tried a lot, but I haven't found a solution. So far in my code I'm able to read from the file, but I can't understand how to save the text line for line and add it to the linked list.
这是我目前所拥有的:
struct list {
char string;
struct list *next;
};
typedef struct list LIST;
int main(void) {
FILE *fp;
char tmp[100];
LIST *current, *head;
char c;
int i = 0;
current = NULL;
head = NULL;
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("Error while opening file.
");
exit(EXIT_FAILURE);
}
printf("File opened.
");
while(EOF != (c = fgetc(fp))) {
printf("%c", c);
}
if(fclose(fp) == EOF) {
printf("
Error while closing file!");
exit(EXIT_FAILURE);
}
printf("
File closed.");
}
如果有人能就我接下来需要做的事情给我一些指示,我将不胜感激.我习惯了Java,不知怎么我的大脑无法理解如何用C来做这些事情.
If anyone could give me some pointers on what I need to do next to make it work, I would highly appreciate it. I'm used to Java, and somehow my brain can't understand how to do these things in C.
推荐答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list {
char *string;
struct list *next;
};
typedef struct list LIST;
int main(void) {
FILE *fp;
char line[128];
LIST *current, *head;
head = current = NULL;
fp = fopen("test.txt", "r");
while(fgets(line, sizeof(line), fp)){
LIST *node = malloc(sizeof(LIST));
node->string = strdup(line);//note : strdup is not standard function
node->next =NULL;
if(head == NULL){
current = head = node;
} else {
current = current->next = node;
}
}
fclose(fp);
//test print
for(current = head; current ; current=current->next){
printf("%s", current->string);
}
//need free for each node
return 0;
}
这篇关于c 中的链表(从文件中读取)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!