c语言文件读取并写入链表
时间: 2024-02-02 08:04:56 浏览: 41
以下是一个示例的C语言代码,用于读取文件并将数据存储到链表中:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
char name[50];
char adr[50];
int tel;
struct student* next;
} Student;
Student* createNode() {
Student* newNode = (Student*)malloc(sizeof(Student));
newNode->next = NULL;
return newNode;
}
void insertNode(Student** head, Student* newNode) {
if (*head == NULL) {
*head = newNode;
} else {
Student* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void readFile(char* filename, Student** head) {
FILE* fp;
if ((fp = fopen(filename, "r")) == NULL) {
printf("Cannot open file\n");
exit(1);
}
int n;
printf("How many students? ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
Student* newNode = createNode(); fscanf(fp, "%s", newNode->name);
fscanf(fp, "%s", newNode->adr);
fscanf(fp, "%d", &(newNode->tel));
insertNode(head, newNode);
}
fclose(fp);
}
void displayList(Student* head) {
Student* temp = head;
while (temp != NULL) {
printf("%10s%15s%15d\n", temp->name, temp->adr, temp->tel);
temp = temp->next;
}
}
void freeList(Student* head) {
Student* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
int main(void) {
char filename[50];
printf("Please input filename: ");
scanf("%s", filename);
Student* head = NULL;
readFile(filename, &head);
displayList(head);
freeList(head);
system("pause");
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)