LEC20081027 - Introduction to Computer Programming CSC180...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
Introduction to Computer Programming October 27, 2008 CSC180 Fall 2008, University of Toronto
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Sort lines Given a text file, how to sort the lines in alphabetical order or in line-length order? Code: /* sort_lines.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXLINES 5000 /* max #lines to be sorted */ char *lineptr[MAXLINES]; /* pointers to text lines */ void usage(char *s); int getline(char s[], int lim, FILE *fp); int read_lines(char *lineptr[], int nlines, char *fname); CSC180 Fall 2008, University of Toronto 1
Background image of page 2
void print_lines(char *lineptr[], int nlines); void free_lines(char *lineptr[], int nlines); void quicksort(char *v[], int left, int right, char c); /* read lines from a file and sort them */ int main(int argc, char *argv[]) { int nlines; if (argc < 3) { fprintf(stderr, "error: too few command-line arguments\n"); usage(argv[0]); } if ((nlines = read_lines(lineptr, MAXLINES, argv[2])) >= 0) { if (strcmp(argv[1], "n") == 0) quicksort(lineptr, 0, nlines-1, ’n’); /* sort using line length */ else if (strcmp(argv[1], "a") == 0) quicksort(lineptr, 0, nlines-1, ’a’); /* sort lexicographically */ else usage(argv[0]); print_lines(lineptr, nlines); free_lines(lineptr, nlines); return 0; } else { fprintf(stderr, "error: input too big to sort\n"); CSC180 Fall 2008, University of Toronto 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
return 1; } } /* print usage information */ void usage(char *s) { printf("Usage: %s n|a file\n", s); exit(1); } /* get line into s, return length */ int getline(char s[], int lim, FILE *fp)
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2011 for the course CSC 180 taught by Professor Na during the Fall '01 term at University of Toronto.

Page1 / 15

LEC20081027 - Introduction to Computer Programming CSC180...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online