[英]How can I create a linked list of characters read from a file? C language
So I have this homework wherein I have to translate a text from a file into EuroEnglish but I'm stuck at the part where I have to create a linked list of characters.所以我有这个作业,其中我必须将文件中的文本翻译成 EuroEnglish,但我被困在必须创建字符链接列表的部分。 What seems to be missing in my code?
我的代码中似乎缺少什么? I'm still trying to understand how linked lists works so I apologize if the code below isn't written well.
我仍在尝试了解链表的工作原理,所以如果下面的代码写得不好,我深表歉意。
I also would like to ask for a few tips on how I can implement a function that checks each individual characters and apply the rules of 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;
}
}
Best practices recommend to avoid global.最佳实践建议避免全局。 Here you have used
fd
as a global variable and opened it in main.这里你已经使用
fd
作为全局变量并在 main 中打开它。 Ok until there.好的,直到那里。 Then you read it until end of file in
file_contents
.然后你阅读它直到
file_contents
的文件结束。 It is still fine, but the file pointer is now at end of file...它仍然很好,但文件指针现在位于文件末尾......
When you try to read in converted_file
, getc
immediately returns an end of file... But as fd
is global you did not notice it.当您尝试在阅读
converted_file
, getc
立即返回文件结束......但作为fd
是全球性的,你没有注意到它。 This can be fixed by rewinding the file with fseek(fd, 0, SEEK_SET);
这可以通过使用
fseek(fd, 0, SEEK_SET);
倒带文件来解决fseek(fd, 0, SEEK_SET);
You have another rewind problem inside converted_file
: after all characters have been read, first
points to the last character, but you try to display the file content starting from there.你里面有另一个退问题
converted_file
:所有字符都被读取后, first
点到最后一个字符,但试图显示文件内容从那里开始。 You should insert a first = head;
你应该插入
first = head;
here, or replace the while
lop with:在这里,或将
while
lop 替换为:
for(first=head; first!=NULL; first=first->next) {
printf("%c", first->letter);
}
I have not tried to run it so other problems could remain...我还没有尝试运行它,所以其他问题可能仍然存在...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.