Read list of numbers in txt file and store to array in C

后端 未结 2 1801
夕颜
夕颜 2020-12-15 14:08

I have a list of integers, one number per line and would like to store each of these numbers in an integer array to use later in the program.

For example in java you

2条回答
  •  不思量自难忘°
    2020-12-15 15:04

    Give this a go. You'll be much better off if you read the man pages for each of these functions (fopen(), scanf(), fclose()) and how to allocate arrays in C. You should also add error checking to this. For example, what happens if Integers.txt does not exist or you don't have permissions to read from it? What about if the text file contains more than 100 numbers?

        FILE *file = fopen("Integers.txt", "r");
        int integers[100];
    
        int i=0;
        int num;
        while(fscanf(file, "%d", &num) > 0) {
            integers[i] = num;
            i++;
        }
        fclose(file);
    

提交回复
热议问题