Code snippets:read line words

From C

Jump to: navigation, search
#include <ctype.h>
#include <stdio.h>

int featlinespace(FILE * stream);
int fgetlineword(char * s, int n, FILE * stream);

int main(void) {
    int line = 1;
    char wordbuf[30];
    int count;

    while (!feof(stdin)) {
        /* For each line, print each word */
        printf("Line %d:\n", line++);
        while ((count = fgetlineword(wordbuf, sizeof wordbuf, stdin))) 
          printf("%d: \"%s\"\n", count, wordbuf);
        /* Eat newline */
        fgetc(stdin);
      }
    return 0;
  }

int featlinespace(FILE * stream) {
    int c;
    int rv = 0;

    while ((c = fgetc(stream)) != EOF) {
        if (!isspace(c) || c == '\n') {
            ungetc(c, stream);
            break;
          }
        ++rv;
        continue;
      }
    return rv;
  }

int fgetlineword(char * s, int n, FILE * stream) {
    char * const end = s + n - 1;
    int c = 0;

    featlinespace(stream);
    n = 0;
    while (s < end && (c = fgetc(stream)) != EOF) {
        if (isspace(c)) {
            ungetc(c, stream);
            break;
          }
        *s++ = c;
        ++n;
        continue;
      }
    *s = '\0';
    return n;
  }
Personal tools