Distinguish the getch, getche, fgetc, GETC, getchar, fgets, and gets functions in C Language

Source: Internet
Author: User

 

Two original posts: http://www.cnblogs.com/younes/archive/2010/01/05/1639482.html

Http://blog.csdn.net/cxyol/archive/2006/03/18/628324.aspx

 

FirstTwo functions are not functions in the c Standard Library:

Int getch (void) // read a character from the standard input. When you enter the character on the keyboard, the screen does not display the character you entered. That is, do not bring back the display.

Int getche (void) // read one character from the standard input. when entering the keyboard, the screen displays the entered characters. Echo.

Both functions do not have a buffer. They are contained in the header file conio. h.

Remember that conio. H is not the header file in the C standard library. The C compiler of micorsoft and Borland provides conio. h to create a console text user interface. Generally, Vs and VC files are installed in windows, which can contain the conio. h header file. However, this header file is usually not found in UNIX and Linux systems,/usr/include.

Getch and getche are waiting for the user to input data from the keyboard. After you press a key, you do not need to press Enter. The program runs automatically. In Linux, terminal input is "one pot" by default, that is, the whole line of input is processed together. Generally, this is a convenient method that people want, but it also means that when reading data, you must press the Enter key to indicate that the input data can be obtained after the input row ends. In the game, many provide the "boss key", which is implemented by using these two functions.

 

 

 

In addition to getch and getche, all other header files in the C standard library are included in the header file stdio. h.

Int fgetc (File * stream); // read a character from the stream. The standard input stdin can be used as its real parameter. At this time, one character can be read from the standard input.

Int GETC (File * stream); // equivalent to fgetc, which is implemented by fgetc through macro.

Int getchar (void); // getchar ()

The function waits for input until you pressEnter
(Provided that there is no data in the buffer zone ),Before press ENTER
All input characters are displayed one by one // on the screen. But read-only access is required for each call.
The first character and uses it as the return value of the function.
.

Note: GETC and getchar are both implemented through macro definition using fgetc. For example, the implementation of getchar is: # define getchar () fgetc (stdin ). For the getchar function,Because the input string does not take the first character, it will discard the remaining string.

It is still in our memory, just like opening the gate and releasing the water. After we put the water into the gate, we can open the gate once and then let it off a little, the unlock action is called once until the light is released.
Getchar ()
. The same is true for the string we input. First, we
The input string is placed in the memory buffer.

, We call
Getchar ()
Output the nearest character in the buffer zone, that is, the first character output. After the output, it is released, but there is a string behind it, therefore, we will use a loop to release the first character in the memory one by one until the carriage return is left empty. If it is empty, it will be executed again.
Getchar ()
Stop and wait for your input.

Note:

1. in windows, a carriage return is generated on the keyboard.
2
Characters
:
Carriage Return
('/R ')
And line breaks
('/N ')
. Carriage Return
'/R' (Cr: Carriage Return:
To bring the cursor back to the beginning of this line, line break
('/N') (new line)
Then wrap the line. However, in Linux, only one character '/N' is generated when you press enter on the keyboard'

2. How to clear the content of the input buffer?

If I want
Getchar ()
Every time you wait for user input, you need to clear the buffer. The following describes the methods (different platforms)

C

Standard provisions
Fflush ()

The function is used to refresh the output (
Stdout

. For input (
Stdin

), It is not defined.
However, some compilers also define
Fflush (stdin)
Such as Microsoft's
VC
. Are other compilers also defined?
Fflush (stdin)
To find its manual.
Gcc
The compiler does not define its implementation, so it cannot be used.
Fflush (stdin)
To refresh the input cache.

For unspecified
Fflush (stdin)
Compiler, you can
Use
Fgets ()

Function to refresh the input Cache
(Comparison
Getchar ()
,
Scanf ()
And other functions ). In this way, the carriage return and other inputs left in the input stream can be ignored to keep the next Input
"
Clean
"
. (This is acceptable on any platform)

//...
Char sbuf [1024];
//...
Fgets (s Buf, 1024, stdin );
//...

In
Windows
Of
VC
You can do the following:

For (INT I = 0; I <10; ++ I)

{


Char CH = getchar ();


Fflush (stdin );//
Every time there is a waiting status

}

 


Fgets () is used to read characters from the file referred to by the parameter stream to the memory space referred to by the parameter S until a line break occurs, and until the end of the file is read or the size-1 character has been read, final meetingEnd with null as a string. If gets () is successful, the S pointer is returned. If null is returned, an error occurs.

Char * fgets (char * STR, int num, file * stream );

// Reads a maximum of num characters from the stream to the character array 'str' and stops when a line break is encountered or when a num-1 character is read.

//The string to be read contains the last line break to be read,


It automatically ends with a null character '/0'.

Char * gets (char * Str); // read a string from the standard input stdin and terminate when a line break or end occurs.

// Unlike fgets, num is not specified, so pay attention to the STR size of the character array.

//The character to be read does not include the last line break, but it is automatically followed by a null character '/0'.

Note: There is no macro-defined relationship between fgets and gets. Each of them has its own implementation. The implementation of the worm virus is the "credit" of the function gets ". The task of the gets function is to read a string from the stream. Its caller will tell it where to put the read string. However,The gets () function does not check the buffer size.

If the caller provides a pointer to the stack and the number of characters read by the get () function exceeds the size of the buffer space, get () it will happily write the extra characters into the stack, which overwrites the original content in the stack. For example:

Main ()

{

Char line [512]; // allocate a space of 512 characters on the program Stack

...

Gets (line); // the entry of the worm virus, which can write malicious code into the stack through the extra data

}

 

 

 

Getch and getche are not recommended because they are not functions in the C standard library. The program written with them has poor portability. Different compilers cannot guarantee that they can contain conio. h. Other functions are stream operations and related buffers are available. In addition, we recommend that you use the fgets function instead of the gets function.

In addition, most of these get functions have corresponding put versions.

Int fputc (INT character, file * stream );

Int putc (INT character, file * stream); // implemented by macro definition and fputc

Int putchar (INT character); // implemented by macro definition: # define putchar (c) fputc (C, stdout)

 

Int fputs (const char * STR, file * stream );

Int puts (const char * Str );

Note: There is no macro-defined implementation relationship between the two. Puts (const char * Str) is approximately equivalent to fputs (cosnt char * STR, stdout). The difference is that the former also outputs a '/N'

 

 

 

Finally

EOF is a symbolic constant defined in stdio. H files. The value is-1.
For example:

The fputc function returns a value. If the output is successful, the returned value is the output character. If the output fails, an EOF is returned.

The fgetc function returns a file end mark (EOF) when reading characters. To read characters from a disk file sequentially and display them on the screen, you can:

Ch = fgetc (FP );

While (Ch! = EOF ){

Putchar (CH );

Ch = fgetc (FP );

}

Note,EOF is not an output character, so it cannot be displayed on the screen. Since the ASCII code cannot contain-1, it is appropriate to define the EOF as-1.
When the read character value is equal to-1 (EOF), it indicates that the read character is not a normal character, but a file Terminator. However, the above only applies to reading text files. Currently, ansi c allows a buffer file system to process binary files. The value of binary data read from a certain byte may be-1, which is exactly the value of EOF. This results in the need to read useful data, but it is processed as "End of File ".Feof (FP) is used to test whether the current state of the file pointed to by FP is "End of File"
. To read data from a binary file in sequence, you can:

While (! Feof (FP )){

C = fgetc (FP );

...

}

 

For more information, see the C standard library.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.