Review of elementry program
I have been teaching myself c. This little program parsed out numbers in a file, and prints those divisible by 3. If anyone is willing, can you point out any thing looks like it wrote it in a bad/strange way, errors that I might run into but haven't, or style?
With style, I am not really interested in variable names, formatting, commenting as much as maybe things like choosing a while loop instead of a for loop. I am also interested in any way this might be optimized, not so much through advanced techniques, but more just simple coding choices.
One thing I was wonder was that I put a Macro in my parse_out_num function. Is it bad to use macros in things other than the main function? If its not bad, would I still declare them at the header or in the function?
Thanks to anyone who takes the time to look at this :-) !
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void zero_string (char * string, int ary_size) {
int idx;
for (idx = 0; idx < ary_size; ++idx) {
string[idx] = '\0';
}
}
int parse_out_num(FILE *file, int *array) {
char c;
int state = 0;
#define MAX_NUM_WIDTH 20
int array_idx = 0;
char curr_num[MAX_NUM_WIDTH] = "";
int char_index = 0;
while (1) {
c = fgetc(file);
if ( c == EOF ) { break; }
// 48-56 is ascii range for digit
if ( (c >= 48) && ( c <= 56) ) {
state = 1;
curr_num[char_index] = c;
char_index += 1;
} else {
// No longer a number
if ( state == 1 ) {
// printf("%s\n", curr_num);
array[array_idx] = atoi(curr_num);
array_idx += 1;
}
state = 0;
char_index = 0;
zero_string(curr_num, MAX_NUM_WIDTH);
}
}
return(array_idx);
}
int main() {
FILE *numbers;
int parsed_num[100];
int index;
int numbers_found;
numbers = fopen("numbers.txt", "r");
numbers_found = parse_out_num(numbers, parsed_num);
for (index = 0; index < numbers_found; ++index) {
if ( parsed_num[index] != 0 && (parsed_num[index] % 3) == 0) {
printf("%i\n", parsed_num[index]);
}
}
return(0);
}