Adding to what Salem and Galahad have said:
You are mixing tabs and spaces for indentation. Just use one or the other. Spaces are best.
Not only should you check that argc is 2 to ensure a parameter has been provided, you should also check that the FILE* is not NULL after trying to open the file.
No need to strcpy argv[1] to another buffer. If you want a better name for it, just do:
const char *source_name = argv[1];
No need to copy the 'source_buffer' to the 'print_buffer' just to add the line number. Just print the line number before the line in the printf statement.
The whole 'save_ch', 'save_chp' thing is not well thought out. If the line is too long the printf("%s", line) call will not print a newline (left in the buffer by the fgets). Also, the rest of the line is just thrown away.
The 'while (get_source_line()) ;' structure is kind of dumb and part of the reason there are so many globals. It would probably be better to put the whole program in main.
The "BOOLEAN get_source_line();" problem is caused by having that declaration in main for no purpose (and compiling it as C++). Just remove it.
Here's a rewrite. Still not perfect, though.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_SOURCE_LINE 1024
#define MAX_PRINT_LINE 74 // leave room for line number
#define MAX_DATE_STRING 32
#define LINES_PER_PAGE 50
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: lister SOURCE_FILE");
exit(EXIT_FAILURE);
}
const char *source_name = argv[1];
FILE *file = fopen(source_name, "r");
if (!file) {
perror("Error: cannot open file");
exit(EXIT_FAILURE);
}
char date[MAX_DATE_STRING];
time_t timer;
time(&timer);
strcpy(date, asctime(localtime(&timer)));
char buffer[MAX_SOURCE_LINE];
int line_number = 0;
int page_number = 0;
int line_count = LINES_PER_PAGE;
while (fgets(buffer, MAX_SOURCE_LINE, file) != NULL) {
buffer[strcspn(buffer, "\r\n")] = '\0'; // remove newline
++line_number;
if (++line_count > LINES_PER_PAGE) {
printf("\fPage %d %s %s\n\n",
++page_number, source_name, date);
line_count = 1;
}
char *out = buffer;
int len = strlen(buffer);
if (len == 0) {
printf("%4d:\n", line_number);
continue;
}
while (len > 0) {
char save_ch = '\0';
if (len > MAX_PRINT_LINE) {
save_ch = out[MAX_PRINT_LINE];
out[MAX_PRINT_LINE] = '\0';
}
if (out == buffer)
printf("%4d: %s\n", line_number, out);
else
printf(" %s\n", out);
if (len < MAX_PRINT_LINE)
len = 0;
else {
out[MAX_PRINT_LINE] = save_ch;
out += MAX_PRINT_LINE;
len -= MAX_PRINT_LINE;
}
}
}
return 0;
}