0

I'm trying to write a function that removes the rest of a line in C. I'm passing in a char array and a file pointer (which the char array was read from). The array is only supposed to have 80 chars in it, and if there isn't a newline in the array, read (and discard) characters in the file until you reach it (newline). Here's what I have so far, but it doesn't seem to be working, and I'm not sure what I'm doing wrong. Any help would be greatly appreciated! Here's the given information about what the function should do:

discardRest - if the fgets didn't read a newline than an entire line hasn't been read. This function takes as input the most recently read line and the pointer to the file being read. discardRest looks for the newline character in the input line. If newline character is not in the line, the function reads (and discards) characters from the file until the newline is read. This will cause the file pointer to be positioned to the beginning of the next line in the input file.

And here's the code:

void discardRest(char line[], FILE* file)
{
    bool newlineFound = FALSE;
    int i;
    for(i = 0; i < sizeof(line); i++)
    {
        if(line[i] == '\n') newlineFound = TRUE;
    }
    if(!newlineFound)
    {
        int c = getc(file);
        while(c != '\n')
        {
            c = getc(file);
        }
    }
}
joce
  • 9,624
  • 19
  • 56
  • 74

1 Answers1

0

Your way is much too difficult, besides sizeof always giving the size of its operand, which is a pointer and not the array it points to which you think it is.

fgets has thefollowing contract:

  • return NULL: Some kind of error, do not use the buffer, its content might be indeterminate.
  • otherwise the buffer contains a 0-terminated string, with the last non-0 being the retained '\n' if the buffer and the file were both large enough.

Thus, this should work:

  1. So, use strlen() to get the buffer length.
  2. Determine if a whole line was read (length && [length-1] == '\n').
  3. As appropriate:
    • remove the newline character and return.
    • discard the rest of the line like you tried.
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • I'm not entirely sure what you mean by the line: (length && [length-1] == '\n') im assuming you mean a variable length for the strlen(line), but how does that determine if a whole line has been read? – user2766421 Apr 26 '14 at 18:51
  • 1
    So assume I'm an idiot, because I still don't get it based off the way you explained it – user2766421 Apr 26 '14 at 19:58
  • Ok, that line pre-supposes that `fgets` encountered no error, then checks for immediate end of file signaled by an empty string, thereafter for existence of the newline just before the terminator. – Deduplicator Apr 26 '14 at 20:07