--- joko/Uni/BSArch/01/prime.c 2006/05/12 19:53:48 1.4 +++ joko/Uni/BSArch/01/prime.c 2006/05/12 21:13:49 1.6 @@ -1,29 +1,44 @@ +/* $Id: prime.c,v 1.6 2006/05/12 21:13:49 joko Exp $ */ + #include +#include +#include + +#define BOOL int +#define TRUE 1 +#define FALSE 0 -#define PRINTPRIME(x) if(is_prime(x)) printf("%i\n", x) -#define PRINTERROR(message) printf("ERROR: %s\n", message) +#define PRINTPRIME(x) if (is_prime(x)) printf("%i\n", x) +#define PRINTERROR(message) fprintf(stderr, "ERROR: %s\n", message) -// check for prime number -int is_prime(int number) +/* check for prime number */ +BOOL is_prime(long int number) { int i; for (i=2; i*i <= number; i++) { if ((number % i) == 0) - return 0; + return FALSE; + } + return TRUE; +} + +/* convert from string to long, with error checking */ +long int convert_number(const char *nptr) { + long int number = strtol(nptr, (char **)NULL, 10); + if (number == LONG_MAX) { + PRINTERROR("Number '%s' is not in range of 'long int'."); } - return 1; } int main(int argc, char * argv[]) { - // TODO: segfaults if zero arguments given - // switch/case??? if (argc == 1) { - PRINTERROR("No arguments given, will segfault under cygwin. :-)"); + PRINTERROR("No arguments given."); + return -1; } - // (3) range mode + /* (3) range mode */ if (argc > 2) { int i, j; j = atoi(argv[2]); @@ -31,21 +46,25 @@ PRINTPRIME(i); } - // other modes + /* other modes */ } else { - // try to open file for reading + /* try to open file for reading */ FILE * fp = fopen(argv[1], "r"); - // (1) test-single-number mode: first argument is not a filename + /* (1) test-single-number mode: first argument is not a filename */ if (fp == NULL) { - PRINTPRIME(atoi(argv[1])); + /* PRINTPRIME(atoi(argv[1])); */ + PRINTPRIME(convert_number(argv[1])); - // (2) file mode: read numbers from file + /* (2) file mode: read numbers from file */ } else { char num[11]; - while (fgets(num, 11, fp)) + while (fgets(num, 11, fp)) { + printf("raw: %s\n", num); + printf("num: %i\n", atoi(num)); PRINTPRIME(atoi(num)); + } fclose(fp); } }