cinputnull-character

Is it possible to read null characters correctly using fgets or gets_s?


Suppose I want to read from stdin, and let the user input strings that contain null characters. Is this possible with string-input functions like fgets or gets_s? Or do I have to use e.g. fgetc or fread?

Someone here wanted to do this.


Solution

  • Is it possible to read null characters correctly using fgets or gets_s?

    As some of the other answers show, the answer is apparently "Yes -- just barely." Similarly, it is possible to hammer in nails using a screwdriver. Similarly, it is possible to write (what amounts to) BASIC or FORTRAN code in C.

    But none of these things is remotely a good idea. Use the right tool for the job. If you want to drive nails, use a hammer. If you want to write BASIC or FORTRAN, use a BASIC interpreter or a FORTRAN compiler. And if you want to read binary data that might contain null characters, use fread (or maybe getc). Don't use fgets, because its interface was never designed for this task.