getword

This is a discussion on getword within the C Programming forums, part of the General Programming Boards category; I did this function for get a word from a file until reaching EOF. I can compile it without error ...

  1. #1
    john bim
    Guest

    Question getword

    I did this function for get a word from a file until reaching EOF.
    I can compile it without error message, but when I try to run it, it looks to take longtime. I think my loop has problem, who can help me to work out?

    here is the code:

    #include <ctype.h>
    #include <stdio.h>
    #include <string.h>

    char *getword(FILE *fp)
    {
    char ch;
    char *w, *word;
    char buf[BUFSIZ];
    w = buf;
    ch = fgetc(fp);
    while( isspace(ch))
    ;
    if(ch != EOF)
    *w++ = ch;
    *w = '\0';
    word = strdup(w);
    return word;
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,805
    >while( isspace(ch))
    >;
    If ch is whitespace then this is an infinite loop, it will never end because you never get another character. A better way would be:
    Code:
    ch = fgetc(fp); 
    while(isspace(ch)) 
      ch = fgetc(fp);
    Or to remove the redundant calls, you can simply initialize ch to a non-whitespace value and only get a new character from the file inside the loop.

    The second problem is that you only assign one character to the buffer, this should be a loop that gets another character and tests it for both whitespace and EOF. Your ch variable should also be int because EOF is a value that cannot be held by a char.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getword and linked lists
    By nefsan in forum C Programming
    Replies: 7
    Last Post: 03-18-2009, 10:55 PM
  2. Replies: 12
    Last Post: 06-06-2008, 05:26 PM
  3. How to recognize <Enter> with getline()?
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 11-10-2001, 05:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21