--*- coding: utf-8; -*-- INF2270 L?sningsforslag oppgaver uke 6 2013 Oppgave 1 #define STREQ(s1,s2) (strcmp((s1),(s2))==0) Oppgave 2 Det finnes mange l?sninger, blant annet x = MIN(a,b) + 1; x = 1 - MIN(a,4); Disse vil bli ekspandert til henholdsvis x = a #include int main(int argc, char *argv[]) { FILE *f; int nc = 0, nw = 0, nl = 0, /* Antall tegn, ord, linjer */ c, in_word = 0; if (argc != 2) { printf("Usage: wc file\n"); return 1; } f = fopen(argv[1],"r"); if (f == NULL) { printf("wc: %s: No such file or directory\n", argv[1]); return 2; } c = fgetc(f); while (c != EOF) { nc++; if (c == '\n') nl++; if (isspace(c)) { in_word = 0; } else { if (! in_word) nw++; in_word = 1; } c = fgetc(f); } fclose(f); printf("%8d%8d%8d %s\n", nl, nw, nc, argv[1]); return 0; } Oppgave 4 #include #include #include struct line_struct { struct line_struct *next; char contents[203]; /* 200 characters + CR and/or LF + 0-byte */ }; typedef struct line_struct line; line *read_all_lines (FILE *f) { line *first = NULL; char cur_line[203]; while (fgets(cur_line,202,f) != NULL) { line *cur = malloc(sizeof(line)); strcpy(cur->contents, cur_line); /* Insert this line first in the list: */ cur->next = first; first = cur; } return first; } void print_all_lines (line *lp) { while (lp) { printf("%s", lp->contents); lp = lp->next; } } void remove_all_lines (line *lp) { if (lp == NULL) return; remove_all_lines(lp->next); free(lp); } int main (int argc, char *argv[]) { if (argc != 2) { printf("Usage: tac filename\n"); exit(1); } FILE *f = fopen(argv[1],"r"); if (f == NULL) { printf("tac: Cannot read %s!\n", argv[1]); exit(2); } line *data = read_all_lines(f); print_all_lines(data); remove_all_lines(data); data = NULL; return 0; }