3

I have a .txt file that I am using to learn some basic C.

Here is the txt file:

8
12  48  15  65  16  82  9   72

Here is my C program:

#include <stdio.h>
#include <stdlib.h>



int main(int argc, char** argv){

        char num = 0;
        //int[] arr = 0;


        if (argc != 2){
                return 0;
        }

        FILE *inputFile = fopen(argv[1], "r");

        if (inputFile == NULL){
                printf("Error1\n");
                return 0;
        }

        while(!feof(inputFile)){
                num = fgetc(inputFile);
                printf("%c\n",num);
        }

        if(!feof(inputFile)){
                printf("error");
                return 0;
        }

}

My goal is the get an array of the second line, based on the amount of values in the first line.... essentially, we want an array with 8 values, that stores {12, 48, ....}

sgerbhctim
  • 3,420
  • 7
  • 38
  • 60

2 Answers2

4

You are using a wrong function to read integers: in spite of returning an int, function fgetc is reading individual characters (why getchar returns an int?).

In order to read space-separated integers, use fscanf instead, and check the return value to decide that you have reached the end of file:

int n;
while (fscanf(inputFile, " %d", &n) == 1) {
    printf("%d\n", n);
}

Note that the loop above avoids using feof to detect the end of file condition (why using feof is wrong?)

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

If you aim to read a series of numbers (and nothing else), regardless of the number of line breaks in between, you could simply use fscanf as follows:

    int num;
    while(fscanf(inputFile, "%d", &num) == 1) {
            printf("%d\n",num);
    }

Note that fscanf returns the number of values successfully read in according to the format specifier, i.e. it returns 1 as long as an integral value could have been read in (and 0 otherwise).

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58