从文件中读取一个固定长度的整数行(bu

时间:2014-09-30 08:14:39

标签: c file

我尝试逐行读取文件(长度为16),但是在添加到链接列表之前将未知行数存储到整数数组中。这就是我的开始,但是我努力扩展它以阅读多行(因为我不知道会有多少行)。有没有更好的方法来实现我想要的,然后使用当前的方法?

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

2 个答案:

答案 0 :(得分:1)

#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;
}

答案 1 :(得分:0)

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);
    }
}