--- joko/Uni/BSArch/01/prime.c 2006/05/13 09:20:36 1.9 +++ joko/Uni/BSArch/01/prime.c 2006/05/13 12:35:32 1.12 @@ -1,4 +1,4 @@ -/* $Id: prime.c,v 1.9 2006/05/13 09:20:36 joko Exp $ */ +/* $Id: prime.c,v 1.12 2006/05/13 12:35:32 joko Exp $ */ #include #include @@ -11,6 +11,10 @@ #define PRINTPRIME(x) if (is_prime(x)) printf("%i\n", x) #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) @@ -31,14 +35,15 @@ /* convert from string to long int, with error checking */ long int convert_number(const char *nptr) { - errno = 0; char * endptr; long int number = strtol(nptr, &endptr, 10); + + errno = 0; /* invalid characters? */ if (*endptr != '\0') { char message[254]; - snprintf(message, 256, "Could not convert '%s' to a valid number.", nptr); + snprintf(message, 256, "Could not convert '%s' to a valid (integer) number.", nptr); PRINTERROR(message); exit(EXIT_FAILURE); } @@ -86,10 +91,47 @@ /* (2) file mode: read numbers from file */ } else { - char entry[11]; - while (fgets(entry, 11, fp)) { - long int number = convert_number(entry); + char line[MAX_LINE_LENGTH + 1]; + long int number; + int line_length; + long int line_no = 0; + while (fgets(line, MAX_LINE_LENGTH + 1, fp)) { + + /* count line number (for warnings) */ + line_no++; + + line_length = strlen(line); + + /* skip empty lines */ + if (strlen(line) < 2) continue; + + /* line handling: policy = skip exceeding lines */ + + /* line exceeds max length */ + if (line_length == MAX_LINE_LENGTH && line[line_length-1] != '\n') { + char message[254]; + 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 or EOF */ + while (1) { + int charcode = fgetc(fp); + if (charcode == 10 || charcode == EOF) break; + } + + /* skip this line from prime calculation */ + continue; + } + + /* 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); }