user3603183
user3603183

Reputation: 333

Reading a fixed length line of integers from a file (bu

I'm trying to reading a file line by line of integers (that are 16 in length), but unknown number of lines and storing them into an integer array before adding into a linked list. This is what I have started off with, but I'm struggling to extend this to read multiple lines (as I don't know how many there will be). Is there a better way to achieve what I want then using the current method?

int deck[16];
while (fgetc(f) != EOF) {
    for (int i = 0; i < DECK_SIZE; i++) {
        c = fgetc(f);
        tempNum = c - '0';
            if(tempNum < MIN_CARD || tempNum > MAX_CARD) {
                failed = 1;
            }
        deck[i] = (int)tempNum;
    }

    if(fgetc(f) != '\n') { // file too long
        failed = 1;
    }

    //CREATE A NODE, ADD IT TO THE LINKED LIST
}


Example contents of a file (1):   (each line holds 16 numbers)
1234567891234564
9876543211234233

Example contents of a file (2):   (each line holds 16 numbers)
1234567891234562
9876543211234233
2354365457658674
3634645756858665

Upvotes: 0

Views: 88

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

int deck[DECK_SIZE];
int failed = 0;
int c, tempNum, i=0;
while((c = fgetc(f)) != EOF){
    if(i < DECK_SIZE){
        tempNum = c - '0';
        if(tempNum < MIN_CARD || tempNum > MAX_CARD){
            failed = 1;
            fprintf(stderr, "out of range\n");
        } else {
            deck[i++] = tempNum;
        }
    } else {
        if(c != '\n'){
            failed = 1;
            fprintf(stderr, "invalid format\n");
        } else {
            i = 0;
            //CREATE A NODE, ADD IT TO THE LINKED LIST
        }
    }
    if(failed){
        fprintf(stderr, "exit\n");
        exit(EXIT_FAILURE);
    }
}

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249103

#include <stdio.h>

enum {
  DECK_SIZE = 16
};

int main()
{
  char deck[DECK_SIZE + 2];
  while (fgets(deck, sizeof(deck), stdin)) {
    char* ch;
    for (ch = deck; *ch; ++ch) {
      *ch -= '0';
    }
    if (ch - deck!= DECK_SIZE + 1) {
      return 1;
    }

    // CREATE A NODE, ADD IT TO THE LINKED LIST
  }

  return 0;
}

Upvotes: 1

Related Questions