// CSE 303, Spring 2009, Marty Stepp // This program prints the lines of a file in reverse order. // If you run it with a file passed as a command-line parameter, it reads // from that file. If you don't pass a file, it reads from standard input. #include #include #include int main(int argc, char* argv[]) { // argv[1] is the file to read FILE* f; int i; int capacity = 10; int line_count = 0; char** lines; // array of strings char buf[1024]; // buffer to read each line if (argc > 1) { f = fopen(argv[1], "r"); if (!f) { perror("Unable to open file"); return 1; } } else { // printf("Usage: %s FILENAME\n", argv[0]); f = stdin; } lines = (char**) malloc(capacity * sizeof(char*)); while (!feof(f)) { // read a line from the file // useful string functions: strcpy, strdup char* str; fgets(buf, sizeof(buf) - 1, f); if (buf[0] == '\n') { break; } str = strdup(buf); // copy the string onto the heap if (line_count == capacity) { capacity *= 2; lines = (char**) realloc(lines, capacity * sizeof(char*)); } lines[line_count] = str; // put this string into the array line_count++; } for (i = line_count - 1; i >= 0; i--) { printf("%s", lines[i]); free(lines[i]); } free(lines); fclose(f); return 0; }