简体   繁体   中英

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. 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.

#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. Ok until there. Then you read it until end of file in 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. This can be fixed by rewinding the file with 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. You should insert a first = head; here, or replace the while lop with:

for(first=head; first!=NULL; first=first->next) {
    printf("%c", first->letter);
}

I have not tried to run it so other problems could remain...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM