Home > Software design >  What is the difference between ReadConsole and fgets?
What is the difference between ReadConsole and fgets?

Time:10-13

What is the difference between ReadConsole() and fgets()? They seem to be able to read characters from stdin.

I am using Visual Studio 2019.

CodePudding user response:

ReadConsole function:Reads character input from the console input buffer and removes it from the buffer.

fgets:Get a string from a stream.

When should I use ReadConsole?

According to the Doc:

ReadConsole reads keyboard input from a console's input buffer. It behaves like the ReadFile function, except that it can read in either Unicode (wide-character) or ANSI mode. ReadConsole can only be used with a console input buffer handle, ReadFile can be used with other handles (such as files or pipes).

CodePudding user response:

These are different levels of programmation. fgets is a function from the C standard library, which means that it has to be present and behave the same in any C implementation. If you intend your code to be useable on other plaforms or simply are learning the C language, it should be your first choice.

ReadConsole is a function from Windows API. It cannot be used outside a Windows platform, but will exist in any of the Microsoft specific environments, from Visual Basic for Application (Microsoft Office macro system) to C#. If you are building a mixed language application targetting exclusively Windows, it can make sense to use it. Or if for any reason you want to be sure to access the console buffer and not a redirected standard input you should use that.

TL/DR: fgets is the standard C way. ReadConsole should only be used on Windows when you want to be sure to read the keyboard buffer and not a possible redirected standard input.

  • Related