| 11 |
|
|
| 12 |
#define PRINTPRIME(x) if (is_prime(x)) printf("%i\n", x) |
#define PRINTPRIME(x) if (is_prime(x)) printf("%i\n", x) |
| 13 |
#define PRINTERROR(message) fprintf(stderr, "ERROR: %s\n", message) |
#define PRINTERROR(message) fprintf(stderr, "ERROR: %s\n", message) |
| 14 |
|
#define PRINTWARNING(message) fprintf(stderr, "WARNING: %s\n", message) |
| 15 |
|
|
| 16 |
/* check for prime number */ |
/* check for prime number */ |
| 17 |
BOOL is_prime(long int number) |
BOOL is_prime(long int number) |
| 32 |
/* convert from string to long int, with error checking */ |
/* convert from string to long int, with error checking */ |
| 33 |
long int convert_number(const char *nptr) { |
long int convert_number(const char *nptr) { |
| 34 |
|
|
|
errno = 0; |
|
| 35 |
char * endptr; |
char * endptr; |
| 36 |
long int number = strtol(nptr, &endptr, 10); |
long int number = strtol(nptr, &endptr, 10); |
| 37 |
|
|
| 38 |
|
errno = 0; |
| 39 |
|
|
| 40 |
/* invalid characters? */ |
/* invalid characters? */ |
| 41 |
if (*endptr != '\0') { |
if (*endptr != '\0') { |
| 88 |
|
|
| 89 |
/* (2) file mode: read numbers from file */ |
/* (2) file mode: read numbers from file */ |
| 90 |
} else { |
} else { |
| 91 |
char entry[11]; |
char entry[81]; |
| 92 |
while (fgets(entry, 11, fp)) { |
long int number; |
| 93 |
long int number = convert_number(entry); |
long int lineno = 0; |
| 94 |
|
while (fgets(entry, 81, fp)) { |
| 95 |
|
|
| 96 |
|
/* count line number (for warnings) */ |
| 97 |
|
lineno++; |
| 98 |
|
|
| 99 |
|
/* skip empty lines */ |
| 100 |
|
if (strlen(entry) < 2) continue; |
| 101 |
|
|
| 102 |
|
/* line handling: policy = skip exceeding lines */ |
| 103 |
|
|
| 104 |
|
/* if last char is newline, strip it */ |
| 105 |
|
if (entry[strlen(entry)-1] == '\n') { |
| 106 |
|
entry[strlen(entry)-1] = '\0'; |
| 107 |
|
|
| 108 |
|
/* line exceeds max length */ |
| 109 |
|
} else { |
| 110 |
|
char message[254]; |
| 111 |
|
snprintf(message, 256, "Line too long (max 80 chars) in line number: %i", lineno); |
| 112 |
|
PRINTWARNING(message); |
| 113 |
|
|
| 114 |
|
/* eat all characters until newline */ |
| 115 |
|
while (fgetc(fp) != 10); |
| 116 |
|
|
| 117 |
|
/* skip this line from prime calculation */ |
| 118 |
|
continue; |
| 119 |
|
} |
| 120 |
|
|
| 121 |
|
number = convert_number(entry); |
| 122 |
PRINTPRIME(number); |
PRINTPRIME(number); |
| 123 |
} |
} |
| 124 |
fclose(fp); |
fclose(fp); |