Sitzung: Jeden Freitag in der Vorlesungszeit ab 16 Uhr c. t. im MAR 0.005. In der vorlesungsfreien Zeit unregelmäßig (Jemensch da?). Macht mit!

C-Kurs/Cat/Musterlösung: Unterschied zwischen den Versionen

< C-Kurs‎ | Cat
(Die Seite wurde neu angelegt: „<pre>#include <stdio.h> #include <stdlib.h> #include <string.h> #define LNUMBERS (1<<0) #define SHOWENDS (1<<1) void usage(){ printf("mycat <option> <file>:\n"...“)
 
 
(Eine dazwischenliegende Version von einem anderen Benutzer wird nicht angezeigt)
(kein Unterschied)

Aktuelle Version vom 5. März 2013, 17:37 Uhr

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LNUMBERS (1<<0)
#define SHOWENDS (1<<1)

void
usage(){
	printf("mycat <option> <file>:\n"
			"-n\tshow line numbers\n"
			"-E\tprint $ at the end of each line"
			"-h\tthis help\n");
	exit(EXIT_SUCCESS);
}

int
print_file(char *fname, unsigned int opts){
	FILE *f = NULL;
	char buf[1024];
	unsigned long lnumber = 1;
	char format[10];

	if(NULL == (f = fopen(fname, "r"))){
		perror("fopen()");
		return -1;
	}

		
	/* of course it would be better to read the file block-wise but
	   for simplicity we assume lines aren't longer than 1024 chars */
	while(fgets(buf, sizeof(buf), f) && !feof(f)){
		if(opts & LNUMBERS)
			printf("%5lu ", lnumber++);

		if(opts & SHOWENDS){
			buf[strlen(buf) - 1] = 0;
			snprintf(format, sizeof format, "%s", "%s$\n");
		} else
			snprintf(format, sizeof format, "%s", "%s");

		printf(format, buf);
	}
	return 0;
}

int
main(int argc, char **argv){
	int i;
	unsigned int options = 0;
	char *file = NULL;

	if(argc < 2){
		usage();
	}
	for(i = 1; (i + 1 < argc) && argv[i][0] == '-'; i++){
		switch(argv[i][1]){
			case 'n': options |= LNUMBERS; break;
			case 'E': options |= SHOWENDS; break;
			case 'h': usage(); break;
			default: usage(); break;
		}
	}
	file = argv[argc - 1];

	if(print_file(file, options) < 0){
		printf("There was an error opening your file\n");
		return -1;
	}

	return 0;
}