The program reads a .txt file that contains lines of numbers. The first one has one number N and the second one has \$N\$ numbers as the first line says.
The \$N\$ numbers is \$1 \le N \le 1.000.000\$.
The program read the \$N\$ numbers in an array and performs the following procedure:
Read the number one by one backwards in the array and check to find the max value. Every time a new max value is found the int
total
increases by one. In the end we write the total value in an output file.
Is my code well written?
#include <stdio.h>
#include <stdlib.h>
/*---------------------*/
/* defined constants */
/* for restriction */
/*---------------------*/
#define MIN 1
#define MAX 1000000
/*---------------------*/
/* function prototypes */
/*---------------------*/
int main(void);
FILE *read_input(char *filename_r);
int count_children(FILE *input);
int pass_heights(FILE *input, int *children,const unsigned int size);
int chck_tall(const int *children,const unsigned int size);
void write_output(const unsigned short total,char *filename_w);
/*----------------------------------*/
/* start of program - Main Function */
/*----------------------------------*/
int main(void) {
char *filename_r = "xxx.in";
char *filename_w = "xxx.out";
FILE *input = read_input(filename_r);
unsigned int size = count_children(input);
int *children = malloc(size * sizeof(unsigned short));
if (children==NULL)
exit(1); //General application error
pass_heights(input, children, size);
fclose(input);
unsigned short total = chck_tall(children, size);
free(children);
write_output(total,filename_w);
return 0;
}
FILE *read_input(char *filename_r) {
FILE *input = fopen(filename_r, "r");
if(input == NULL)
exit(66); //EXIT_NOINPUT 'cannot open input'
return input;
}
int count_children(FILE *input) {
unsigned int count = 0;
fscanf(input, "%d",&count);
if(count > MAX || count < MIN)
exit(1); //General application error
return count;
}
int pass_heights(FILE *input, int *children,const unsigned int size) {
for(register int i = 0; i < size; i++)
fscanf(input, "%d",&children[i]);
return *children;
}
int chck_tall(const int *children,const unsigned int size) {
unsigned short total = 0;
unsigned short tmp_max = 0;
for(register int i = size - 1; i >= 0; i--)
{
if(children[i] > tmp_max) {
tmp_max = children[i];
total++;
}
}
return total;
}
void write_output(const unsigned short total,char *filename_w) {
FILE *output = fopen(filename_w, "w");
if(output == NULL)
exit(74); //EXIT_IOERR 'input/output error'
fprintf(output, "%d\n", total);
fclose(output);
}