+ 1
How is the last minimum number of a sequence from a file without using an array?
I have a file "input.txt" In which there are integers. I need to determine the last minimum number.
1 Answer
0
There is no need to use array. You will need only 2 variables which will store the number you read and a minimum.
$ cat input.txt
1 42 56 9 -2 13 -18 20 33 55 -8 43 1 2
./a.out
Last minimum number is -18
$cat lastMin.c
// I have a file "input.txt" In which there are integers.
// I need to determine the last minimum number.
#include <stdio.h>
#include <stdlib.h>
int main() {
// create a pointer to a file
FILE *pFile;
// create two variables
int number = 0;
int min = 0;
// open file
pFile = fopen("input.txt", "r");
// check if the file successfully opened
if (NULL == pFile ) {
printf("Could not open file!");
return 1;
}
// EOF is a pointer for file ending
// fscanf read from file an integer into a variable `number`
while (fscanf(pFile, "%d", &number) != EOF) {
// if the current number is less than min, we found a minimum
if (number < min) {
min = number;
}
}
// print last minimum we got after reading file
printf("Last minimum number is %d\n", min);
// after we finished work with file we have to close file.
fclose(pFile);
return 0 ;
}