--- joko/Uni/BSArch/01/prime.c 2006/05/12 19:03:04 1.3 +++ joko/Uni/BSArch/01/prime.c 2006/05/12 21:13:49 1.6 @@ -1,33 +1,70 @@ +/* $Id: prime.c,v 1.6 2006/05/12 21:13:49 joko Exp $ */ + #include -#define PRINTPRIME(x) if(prime(x)) printf("%i\n", x) +#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) fprintf(stderr, "ERROR: %s\n", message) -int 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 1; + int i; + for (i=2; i*i <= number; i++) { + if ((number % i) == 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'."); + } } int main(int argc, char * argv[]) { - int i, j; - FILE * fp; - char num[11]; - if(argc > 2 ){ - j=atoi(argv[2]); - for(i=atoi(argv[1]) ; i< j; i++){ + + if (argc == 1) { + PRINTERROR("No arguments given."); + return -1; + } + + /* (3) range mode */ + if (argc > 2) { + int i, j; + j = atoi(argv[2]); + for (i = atoi(argv[1]); i< j; i++) { PRINTPRIME(i); } - }else { - fp=fopen(argv[1], "r"); - if(fp==NULL){ - PRINTPRIME(atoi(argv[1])); - }else{ - while(fgets(num, 11, fp)) + + /* other modes */ + } else { + + /* try to open file for reading */ + FILE * fp = fopen(argv[1], "r"); + + /* (1) test-single-number mode: first argument is not a filename */ + if (fp == NULL) { + /* PRINTPRIME(atoi(argv[1])); */ + PRINTPRIME(convert_number(argv[1])); + + /* (2) file mode: read numbers from file */ + } else { + char num[11]; + while (fgets(num, 11, fp)) { + printf("raw: %s\n", num); + printf("num: %i\n", atoi(num)); PRINTPRIME(atoi(num)); + } fclose(fp); } }