Created
June 27, 2021 23:33
-
-
Save veganaize/ec5433f5874285d1bd065fcdb0cd7a77 to your computer and use it in GitHub Desktop.
Wrap words at column boundary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Only works with LF, not CRLF or CR | |
* Characters are presumed to be 7-bits. | |
* Tabs only count as one character. | |
*/ | |
#include <stdio.h> | |
#include <ctype.h> /* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment