khalfella

ansi_c_pg34_ch01_e22.c

Sep 28th, 2014
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. /*
  2. * Exercise 1-22.
  3. * Write a program to ``fold'' long input lines into two or more shorter lines
  4. * after the last non-blank character that occurs before the n-th column of
  5. * input. Make sure your program does something intelligent with very long
  6. * lines, and if there are no blanks or tabs before the specified column.
  7. */
  8.  
  9.  
  10. # include <stdio.h>
  11.  
  12. #define TABSTOP 8
  13. #define LINESIZE 20
  14. #define WORDSIZE (3 * LINESIZE)
  15.  
  16.  
  17.  
  18. int
  19. get_word(char *word, int lim) {
  20. int len = 0;
  21. int c;
  22.  
  23.  
  24.  
  25. while (len < lim - 1 && (c = getchar()) != EOF) {
  26. if (c == ' ' || c == '\n' || c == '\t') {
  27. word[len++] = c;
  28. word[len] = '\0';
  29. return len;
  30. }
  31. word[len++] = c;
  32. }
  33.  
  34. word[len] = '\0';
  35. return len;
  36.  
  37. }
  38.  
  39. int
  40. main() {
  41.  
  42. char word[WORDSIZE];
  43. int len;
  44. int offset = 0;
  45. int last;
  46. int i;
  47. int complete;
  48.  
  49. while ((len = get_word(word, WORDSIZE)) != 0) {
  50.  
  51. last = word[len - 1];
  52.  
  53. /* can we just print the whole word in the current line*/
  54. if (offset + len <= LINESIZE - 1) {
  55. printf("%s",word);
  56. offset +=len;
  57. /* reset offset if it ends with '\n' */
  58. if (word[len - 1] == '\n') {
  59. offset = 0;
  60. }
  61. } else {
  62. /* shall we start new line now */
  63. if (LINESIZE - offset <= 1 ) {
  64. putchar ('\n');
  65. offset = 0;
  66. }
  67. /* print the word */
  68. for (i = 0; i < len; i++) {
  69.  
  70. /*
  71. * when we are close to the end of th line and there are still
  72. * few characters left, then we have no option but to hyphenate
  73. * the word
  74. */
  75. if (offset == LINESIZE - 2 && (len -i -1) > 2) {
  76. putchar('-');
  77. putchar('\n');
  78. offset = 0;
  79. }
  80.  
  81. putchar(word[i]);
  82. offset++;
  83. }
  84.  
  85. /* if the word ends with '\n', then reset offset */
  86. if (word[i - 1] == '\n') {
  87. offset = 0;
  88. }
  89.  
  90. }
  91.  
  92. }
  93. return (0);
  94. }
Advertisement
Add Comment
Please, Sign In to add comment