C Read File Line by Line Into Array
C program to read numbers from a file and store them in an array:
In this post, nosotros 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 dissimilar number values. The C plan volition read all these values from that file and put them in an assortment. Likewise, information technology will print the assortment content.
Create the text file:
For this case, create one file testfile.txt with the below text:
C Program:
Below C program will read the numbers from the above text file and put them in an array. Create one instance.c file in the same folder of testfile.txt with the below lawmaking:
# include <stdio.h> int chief ( void ) { int numbers[ fifty ] ; 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] ) ; } render 0 ; } Hither,
- numbers is an array to concord the numbers
- file is the file pointer. This file pointer is used to hold the file reference once it is open.
- Using fopen, we are opening the file in read more than. The r is used for read manner. If the file is opened using fopen, information technology scans the content of the file.
- The while loop reads the file and puts the content i.e. the numbers in the numbers array. The i is used to indicate to the electric current location in the array. Information technology starts from 0 and information technology is incremented by 1 on each iteration.
- Once the while loop ends, nosotros are endmost the file using fclose. Also, as the reading is completed, we are adding \0 at the finish of the array.
- The final for loop is used to print the contents of the numbers assortment, i.e. the numbers of the text file.
Output:
Information technology volition impress the contents of the file, i.due east. the numbers.
You might besides similar:
- C programme to bank 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
- Departure between %d and %i format specifiers in C
- Write a C programme to add ii distances using structure
- Example of fseek() in C
- C program to observe the missing number in an assortment
Source: https://www.codevscolor.com/c-read-numbers-file-store-array
0 Response to "C Read File Line by Line Into Array"
Postar um comentário