Reading an array of integers from a file
This example uses the feof() function to read from the file until it is empty.
Obviously, I am assuming the file consists of a list of 20 or fewer integers
and that the last integer is on the last line of the file (i.e. no extraneous
lines at the end of the file).
#include <stdio.h>
int main(void)
{
FILE *ptr;
int index, array[20], i = 0, flag, temp;
ptr = fopen("test.dat", "r");
while (!feof(ptr))
{
flag = fscanf(ptr, "%d", &temp);
if (flag == 1)
{
array[i] = temp;
i++;
}
}
fclose(ptr);
i--;
printf("\n");
for (index = 0; index <= i; index++)
printf("%d ", array[index]);
printf("\n\n");
return (0);
}
This example simply compares the return value of the fscanf() to EOF to
determine whether the end of the file has been reached. As with the first
example, no error checking has been done.
#include <stdio.h>
int main(void)
{
FILE *ptr;
int index, array[20], i = 0, flag, temp;
ptr = fopen("test.dat", "r");
do
{
flag = fscanf(ptr, "%d", &temp);
if (flag == 1)
{
array[i] = temp;
i++;
}
}
while (flag != EOF);
fclose(ptr);
i--;
printf("\n");
for (index = 0; index <= i; index++)
printf("%d ", array[index]);
printf("\n\n");
return (0);
}
This is the file I used to test the 2 samples. The 1 is the first character in
the file and the 89 is on the last line (i.e. no carriage return or white space
followed the 89).
1
5
7
3
9
87
467
89