C program to read numbers from a file and store them in an array:
In this post, we will learn how to read numbers from a text file and store them in an array in C. One text file is given and this file holds different number values. The C program will read all these values from that file and put them in an array
. Also, the program will print the array contents.
Create the text file:
For this example, create one file testfile.txt
and add the following content:
10
20
30
40
50
You can modify the content or change the name of the text file. But make sure to update the file name in the program below.
C Program to read numbers of a file and add them to an array:
The following C program will read the numbers from the above text file and put them in an array. You need to create one example.c
file in the same folder with the text file testfile.txt
to use the below code:
#include <stdio.h>
int main(void)
{
int numbers[50];
int i = 0;
FILE *file;
if (file = fopen("testfile.txt", "r"))
{
while (fscanf(file, "%d", &numbers[i]) != EOF)
{
i++;
}
fclose(file);
numbers[i] = '\0';
for (i = 0; numbers[i] != '\0'; i++)
printf("%d\n", numbers[i]);
}
return 0;
}
Download it on Github
Here,
- The
numbers
variable is an array to hold the numbers. - The
file
is the file pointer variable. This file pointer is used to hold the file reference once it is open. - By using the
fopen
method, we are opening the file in read mode. The second parameterr
is used for the read mode. If the file path is valid and if the file can be opened in read mode, it will run the code in theif
block. - The
while
loop reads the file content and puts the content i.e. the numbers in thenumbers
array. Thei
variable is used to point to the current location in the array. It starts from 0 and it is incremented by 1 on each iteration. - Once the
while
loop ends, we are closing the file with thefclose
method. Also, once the reading is completed, we are adding the NULL character\0
at the end of the array. - The last
for
loop is used to print the contents of thenumbers
array, i.e. the numbers of the text file.
Output:
It will print the contents of the file, i.e. the numbers.
You might also like:
- C program to check if a character is a vowel or consonant
- C program to print squares and cubes of all numbers from 1 to n
- How to declare a variable dynamically in C
- Difference between %d and %i format specifiers in C
- Write a C program to add two distances using structure
- Example of fseek() in C
- C program to find the missing number in an array