--- joko/Uni/BSArch/01/prime.c 2006/05/13 12:06:38 1.10 +++ joko/Uni/BSArch/01/prime.c 2006/05/13 12:30:54 1.11 @@ -1,4 +1,4 @@ -/* $Id: prime.c,v 1.10 2006/05/13 12:06:38 joko Exp $ */ +/* $Id: prime.c,v 1.11 2006/05/13 12:30:54 joko Exp $ */ #include #include @@ -13,6 +13,9 @@ #define PRINTERROR(message) fprintf(stderr, "ERROR: %s\n", message) #define PRINTWARNING(message) fprintf(stderr, "WARNING: %s\n", message) +#define MAX_LINE_LENGTH 80 + + /* check for prime number */ BOOL is_prime(long int number) { @@ -88,38 +91,47 @@ /* (2) file mode: read numbers from file */ } else { - char entry[81]; + char line[MAX_LINE_LENGTH + 1]; long int number; - long int lineno = 0; - while (fgets(entry, 81, fp)) { + int line_length; + long int line_no = 0; + while (fgets(line, MAX_LINE_LENGTH + 1, fp)) { /* count line number (for warnings) */ - lineno++; + line_no++; + line_length = strlen(line); + /* skip empty lines */ - if (strlen(entry) < 2) continue; + if (strlen(line) < 2) continue; /* line handling: policy = skip exceeding lines */ - /* if last char is newline, strip it */ - if (entry[strlen(entry)-1] == '\n') { - entry[strlen(entry)-1] = '\0'; - /* line exceeds max length */ - } else { + if (line_length == MAX_LINE_LENGTH && line[line_length-1] != '\n') { char message[254]; - snprintf(message, 256, "Line too long (max 80 chars) in line number: %i", lineno); + snprintf(message, 256, "Line too long (max %i chars) in line number: %i", MAX_LINE_LENGTH, line_no); PRINTWARNING(message); - /* eat all characters until newline */ - while (fgetc(fp) != 10); + /* eat all characters until newline or EOF */ + while (1) { + int charcode = fgetc(fp); + if (charcode == 10 || charcode == EOF) break; + } /* skip this line from prime calculation */ continue; } - number = convert_number(entry); + /* if last char is newline, strip it */ + if (line[line_length-1] == '\n') { + line[line_length-1] = '\0'; + } + + /* finally: prime number calculation and output */ + number = convert_number(line); PRINTPRIME(number); + } fclose(fp); }