/* Only works with LF, not CRLF or CR * Characters are presumed to be 7-bits. * Tabs only count as one character. */ #include #include /* isspace() */ #define COLUMNS 10 int main() { FILE *infile, *outfile; long last_white_in = 0; int in_char, line_length, word_length; /* Open files... */ if ((infile = fopen("infile.txt", "rb")) != NULL) { puts("Successfully opened input file."); } else { puts("Unable to open input file."); return 1; } if ((outfile = fopen("outfile.txt", "wb")) != NULL) { puts("Successfully opened output file."); } else { puts("Unable to open output file."); return 2; } /* Iterate over files while inserting newlines */ for (in_char = fgetc(infile), line_length = 0; !feof(infile); in_char = fgetc(infile)) { /* Input at end of line ? */ if (in_char == '\n') { fputc('\n', outfile); line_length = 0; continue; } /* Wrap long output line ? */ if (++line_length > COLUMNS) { word_length = ftell(infile) - last_white_in; /* No whitespace to break on ? */ if (COLUMNS < word_length) { fputc('\n', outfile); fseek(infile, -1, SEEK_CUR); /* Whitespace to break on ? */ } else { fseek(infile, word_length*-1, SEEK_CUR); fseek(outfile, word_length*-1, SEEK_CUR); fputc('\n', outfile); } last_white_in = ftell(infile); line_length = 0; continue; } /* Mark last occurance of whitespace */ if (isspace(in_char)) last_white_in = ftell(infile); /* Copy input character to output */ fputc(in_char, outfile); } fclose(infile); fclose(outfile); return 0; }