[英]How can I create a (C) function to read data from a file into a linked-list using 'read'?
[英]How can I create a linked list of characters read from a file? C language
所以我有这个作业,其中我必须将文件中的文本翻译成 EuroEnglish,但我被困在必须创建字符链接列表的部分。 我的代码中似乎缺少什么? 我仍在尝试了解链表的工作原理,所以如果下面的代码写得不好,我深表歉意。
我还想请教一些关于如何实现检查每个字符并应用 EuroEnglish 规则的功能的提示。
#include <stdio.h>
#include <stdlib.h>
void file_contents();
void converted_file();
FILE *fp;
char c;
int i = 0;
struct L;
struct L
{
char letter;
struct L *next;
};
int main(int argc, char *argv[])
{
if (argc != 2)
printf("USAGE: %s <filename>", argv[0]);
else
{
fp = fopen(argv[1], "r");
if (fp == 0)
{
printf("Could not open file.\n");
exit(1);
}
else
{
file_contents();
converted_file();
fclose(fp);
}
}
}
void file_contents()
{
printf("\nYour file contains:\n\n");
while ((c = getc(fp)) != EOF)
printf("%c", c);
printf("\n");
}
void converted_file()
{
struct L *first, *tail, *head;
printf("\nText converted in EuroEnglish:\n");
while ((c = getc(fp)) != EOF)
{
first = (struct L *) malloc(sizeof(struct L));
first->letter = c;
first->next = NULL;
if (tail == NULL)
head = tail = first;
else
{
tail->next = first;
tail = first;
}
}
while (first != NULL)
{
printf("%c", first->letter);
first = first->next;
}
}
最佳实践建议避免全局。 这里你已经使用fd
作为全局变量并在 main 中打开它。 好的,直到那里。 然后你阅读它直到file_contents
的文件结束。 它仍然很好,但文件指针现在位于文件末尾......
当您尝试在阅读converted_file
, getc
立即返回文件结束......但作为fd
是全球性的,你没有注意到它。 这可以通过使用fseek(fd, 0, SEEK_SET);
倒带文件来解决fseek(fd, 0, SEEK_SET);
你里面有另一个退问题converted_file
:所有字符都被读取后, first
点到最后一个字符,但试图显示文件内容从那里开始。 你应该插入first = head;
在这里,或将while
lop 替换为:
for(first=head; first!=NULL; first=first->next) {
printf("%c", first->letter);
}
我还没有尝试运行它,所以其他问题可能仍然存在...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.