0

I want to read a sequence of digits, character by character, from a .txt file until I find a \n character, this is, until I find an enter. Then to transform each of those digits into integers, and make a linked list to store those integers. The number of digits is undefined, it can either be 1 or 1 000 000. This is what I have done so far, but I just can't get my head around on how to transform them into ints, how make the actual list and then print it.

void make_seq_list ()
    {
        struct seq_node *seq_current = seq_head;

        int digit_;

        printf("sequence:\n");

        while ( (digit_ = fgetc("fptr")) != '\n')
        {
            //???
        }
    }

This is how I defined each node for this list:

typedef struct seq_node //declaration of nodes for digit sequence list
{
    int digit; //digit already as an int, not char as read from the file
    struct seq_node *next;
} seq_node_t;

Note that in the txt file, the sequence is something like:

1 2 3 1 //it can go on indefinitely
/*something else*/

Thanks in advance.

  • `fgetc("fptr")`is totally wrong and doesn't make any sens. Read the documentation. For the rest you need to come up with some code. I'm sure the relevant information is somewhere in your lecture notes. Otherwise google "linked list C" you should stumble upon something, there are tons of tutorials. Also read this: [ask] – Jabberwocky May 15 '20 at 09:30
  • This might get you started: https://stackoverflow.com/questions/4600797/read-int-values-from-a-text-file-in-c/4601150 –  May 15 '20 at 09:32

1 Answers1

0
digit_ = fgetc("fptr")

It's totally wrong. The declaration of fgetc function:

 int fgetc(FILE *stream);

So, if you want to read the context of the file, you have to open it first:

FILE * fptr = fopen("filename", "r"); // filename: input.txt for example.
if(!fptr) {
   // handle the error.
}

// now, you can read the digits from the file.
int c = fgetc(fp); 

If your file contents only the digits (from 0 to 9), you can use fgetc to read digit by digit. The peusedo-code:

    FILE * fptr = fopen("input.txt", "r");
    if(!fptr) {
       // handle the error.
    }
     while(1) {
        int c = fgetc(fp);
        if(isdigit(c)) {
            int digit = c-'0';
            // add "digit" to linked list
        } else if (c == '\n') { // quit the loop if you meet the enter character
            printf("end of line\n");
            break;
        } else if(c == ' ') { // this line is optional
            printf("space character\n");
        }
    }

    // print the linked list.

For inserting or printing the linked list, you can search in google. There will be a ton of examples for you. For example, example of inserting and printing linked-list

Hitokiri
  • 3,607
  • 1
  • 9
  • 29