如何用fwrite将文件读取到链表
时间: 2023-05-20 17:01:47 浏览: 66
首先,我们需要定义一个结构体来表示链表中的每个节点,包含文件中读取的数据和指向下一个节点的指针。然后,我们可以使用fopen函数打开文件,使用fread函数读取文件中的数据,并将数据存储到链表中的节点中。最后,使用fwrite函数将链表中的数据写入到另一个文件中。
以下是示例代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
char data[100];
struct Node* next;
};
int main() {
FILE* fp = fopen("input.txt", "rb");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
struct Node* head = NULL;
struct Node* tail = NULL;
while (!feof(fp)) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Failed to allocate memory\n");
return 1;
}
int bytesRead = fread(newNode->data, sizeof(char), 100, fp);
if (bytesRead == 0) {
free(newNode);
break;
}
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
fclose(fp);
FILE* fpOut = fopen("output.txt", "wb");
if (fpOut == NULL) {
printf("Failed to open output file\n");
return 1;
}
struct Node* curr = head;
while (curr != NULL) {
fwrite(curr->data, sizeof(char), 100, fpOut);
curr = curr->next;
}
fclose(fpOut);
curr = head;
while (curr != NULL) {
struct Node* temp = curr;
curr = curr->next;
free(temp);
}
return 0;
}
```