Search code examples
cscanffgetsstdiofseek

Would it be a bad practice to mix fgets with scanf and use fseek to skip the new line characters? C


I want to use fgets and scanf mixing them, but there are leftovers of '\n' characters and they mess up the fgets output, I've tried using:

fseek(stdin, 0, SEEK_END);

And it worked, is this a bad practice?


Solution

  • The behaviour of fseek with SEEK_END isn't defined by the C standard.

    7.21.9.2/4 The fseek function:

    For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

    Even otherwise, It's unreliable to use fseek on stdin. POSIX says streams with no backing files (pipes, sockets, etc) are not seekable.

    But you're attempting a "wrong" solution in my view: don't mix fgets and scanf to start with.

    scanf is fragile for user inputs and proper error handling of scanf is hard. You might instead use just fgets to read lines and use sscanf to extract inputs.