INF2270 Løsningsforslag oppgaver uke 6 2010 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[204]; }; typedef struct line_struct line; line *read_all_lines (void) { line *first = NULL, *last = NULL, *cur; char cur_line[204]; while (fgets(cur_line,200,stdin) != NULL) { cur = malloc(sizeof(line)); strcpy(cur->contents, cur_line); /* Insert this line last in the list: */ if (first == NULL) { first = cur; last = cur; } else { last->next = cur; last = cur; } last->next = NULL; } return first; } void print_all_lines (line *lp) { while (lp) { printf("%s", lp->contents); lp = lp->next; } } int main (void) { line *data = read_all_lines(); print_all_lines(data); return 0; }