Gets function с linux

gets (3p) — Linux Manuals

This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.

NAME

gets — get a string from a stdin stream

SYNOPSIS

char *gets(char *s);

DESCRIPTION

The gets() function shall read bytes from the standard input stream, stdin, into the array pointed to by s, until a is read or an end-of-file condition is encountered. Any shall be discarded and a null byte shall be placed immediately after the last byte read into the array.

The gets() function may mark the st_atime field of the file associated with stream for update. The st_atime field shall be marked for update by the first successful execution of fgetc(), fgets(), fread(), getc(), getchar(), gets(), fscanf(), or scanf() using stream that returns data not supplied by a prior call to ungetc().

RETURN VALUE

Upon successful completion, gets() shall return s. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and gets() shall return a null pointer. If a read error occurs, the error indicator for the stream shall be set, gets() shall return a null pointer, and set errno to indicate the error.

ERRORS

The following sections are informative.

EXAMPLES

APPLICATION USAGE

Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.

Since the user cannot specify the length of the buffer passed to gets(), use of this function is discouraged. The length of the string read is unlimited. It is possible to overflow this buffer in such a way as to cause applications to fail, or possible system security violations.

It is recommended that the fgets() function should be used to read input lines.

RATIONALE

FUTURE DIRECTIONS

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology — Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

SEE ALSO

feof(), ferror(), fgets(), the Base Definitions volume of IEEE Std 1003.1-2001,

  • gets (3) — get a string from standard input (DEPRECATED)
  • gets (n) — Read a line from a channel
  • getservbyname (3p)
  • getservbyport (3p)
  • getservent (3p)
  • getsid (3p) — get the process group ID of a session leader
  • getsockname (3p) — get the socket name
  • getsockopt (3p) — get the socket options
  • getsubopt (3p) — parse suboption arguments from a string
  • getaddrinfo (3p) — get address information
  • catgets (3p) — read a program message
Читайте также:  Загрузочная флешка linux 32 bit

Источник

Gets function с linux

fgetc() считывает очередной символ из потока stream и возвращает преобразованный unsigned char в int или возвращает константу EOF по достижении конца файла или при возникновении ошибки.

getc() похожа на fgetc() , но она может быть реализована как макрос, который определяет состояние stream более одного раза.

getchar() эквивалентна getc( stdin ) .

gets() считывает строку из stdin и записывает ее в буфер, на который указывает s, пока не встретится символ новой строки или EOF , которые заменяются значением ‘\0’ . Проверка на переполнение буфера не производится (см. ЗАМЕЧАHИЯ ниже).

fgets() считывает максимум size — 1 символов из stream и заносит их в буфер, на который указывает s . Чтение прерывается по достижении EOF или символа новой строки. Если считан символ новой строки, то он заносится в буфер. В конце к строке добавляется ‘\0’ .

ungetc() заносит c обратно в stream , преобразует в unsigned char , если это возможно для дальнейших операций чтения. Занесенные обратно символы будут возвращаться в обратном порядке; гарантируется только одно занесение символов.

Вызовы функций, описанные здесь, могут смешиваться друг с другом и с другими функциями ввода из библиотеки stdio для того же потока ввода.

ВОЗВРАЩАЕМЫЕ ЗНАЧЕНИЯ

fgetc() , getc() и getchar() возвращают символ, считанный как unsigned char и преобразованный в int ; а также возвращают EOF по достижении конца файла или при возникновении ошибки.

gets() и fgets() возвращают s при удачном завершении операции и NULL при ошибке или если достигнут конец файла, а символы остались несчитанными.

ungetc() возвращает c при удачном завершении операции или EOF при возникновении ошибки.

СООТВЕТСТВИЕ СТАНДАРТАМ


НАЙДЕННЫЕ ОШИБКИ

Hикогда не применяйте в работе gets() , потому что без предварительного знакомства с данными невозможно узнать, какое количество символов считает gets() , а также потому, что gets() будет продолжать заносить символы в буфер даже по достижении его конца, что представляет собой большую опасность. Эта функция использовалась для взлома систем безопасности компьютера. Вместо этой функции используйте fgets() .

Hе рекомендуется чередовать вызовы функций ввода библиотеки stdio с низкоуровневыми вызовами read() для описателя файла, связанного с потоком ввода; результат этого будет неопределенным и, скорее всего, не тем, который ожидается.

Источник

gets(3) — Linux man page

fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.

getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.

getchar() is equivalent to getc(stdin).

gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with a null byte (aq\0aq). No check for buffer overrun is performed (see BUGS below).

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.

Читайте также:  Ocs inventory linux server

ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.

Calls to the functions described here can be mixed with each other and with calls to other input functions from the stdio library for the same input stream.

For nonlocking counterparts, see unlocked_stdio(3).

Return Value

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

gets() and fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read.

ungetc() returns c on success, or EOF on error.

Conforming to

LSB deprecates gets(). POSIX.1-2008 marks gets() obsolescent. ISO C11 removes the specification of gets() from the C language, and since version 2.16, glibc header files don’t expose the function declaration if the _ISOC11_SOURCE feature test macro is defined.

Bugs

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very probably not what you want.

See Also

read(2), write(2), ferror(3), fgetwc(3), fgetws(3), fopen(3), fread(3), fseek(3), getline(3), getwchar(3), puts(3), scanf(3), ungetwc(3), unlocked_stdio(3), feature_test_macros(7)

Источник

Why there is no «gets» function in C standard library?

If you are new to learn C programming, you may find there are many functions like «getc», «putc», «getchar», «putchar», «fgets», «fputs» : every «put» function comes with a corresponding «get» function. But there is a «puts» function while no «gets» function. Why? Well, the short anwer is, the «gets» function was there before in C89 standard, then it got deprecated in C99 and removed in C11. But let’s see why it got removed. First let’s check the function’s declaration:

Basically we pass a pre-allocated «str» buffer to this function, gets will get user’s input and save it into this buffer. So we can write some code like this:

char buffer[20] = 0>; gets(buffer); printf("Your input is: %s\n", buffer); 

We can see using this function is dangerous, but if we ignore this warning and go ahead run our program: if we type «hello world» as our input, the program can correctly put this string out. So why is it dangerous? In our program we allocated a char array which has 20 slots, and our input «hello world» which are 11 characters, will be saved inside this array from position 0. Our «hello world» case works well, but now imagine what if our input has more than 20 characters, then we won’t have enough space to save all of these characters:

$ ./main hello world hello world hello world Your input is: hello world hello world hello world *** stack smashing detected ***: terminated Aborted (core dumped) 

In this case, since we don’t have enough space to save user’s input, the program crashed. Sometimes this may cause bug that harder to find, suppose we have code like this:

#include int main()  char c = 'c'; char arr[10] = 0>; printf("before gets: variable c is %c\n", c); gets(arr); printf("after gets: variable c is %c\n", c); return 0; > 

Before we compile and run the code, guess what the output would be if in the gets step, we type «hello world». Your guess might be the program will crash since «hello world» in total are 11 characters (including the white-space in the middel) but our allocated arr only have 10 slots. Well, you are not wrong with the modern compiler, by that I mean, if we compile the code and run it:

$ gcc main.c -o main main.c:(.text+0x51): warning: the 'gets' function is dangerous and should not be used. $ ./main before gets: variable c is c hello world after gets: variable c is c *** stack smashing detected ***: terminated Aborted (core dumped) 

But in the old compiler, you might won’t have this crashed. The modern gcc will compile with a default «stack-protector» turned on. Let’s try to turn it off then run again:

$ gcc main.c -fno-stack-protector -o main main.c:(.text+0x42): warning: the 'gets' function is dangerous and should not be used. $ ./main before gets: variable c is c hello world after gets: variable c is d 

Ah, this time the program doesn’t crash. But our variable ‘c’ which is declared before arr has been «magically» changed to the character ‘d’, which is the last letter in «world». To understand this, we need to know how the program allocate spaces in stack. Most of the operating system will allocate stack from high address to low address. The stack in our program will be something like this:
When we input «hello world», program will try to save this string from arr[0] , like this:
So technically we still have 11 slots, but the last one is not for our array, it is the space for our variable c . When the program saved the whole string, it put the last letter ‘d’ in our char c slot — that’s why after input our varaible c has been modified to d ! This kind bug is quite dangerous and not easy to find!

The solution

char* fgets(char *string, int length, FILE * stream); 
#include int main()  char c = 'c'; char arr[10] = 0>; printf("before gets: variable c is %c\n", c); fgets(arr, 10, stdin); printf("after gets: variable c is %c\n", c); return 0; > 
$ gcc main.c -o main $ ./main before gets: variable c is c hello world after gets: variable c is c 

Two things changed here: 1) when compile, there is no warning info printed out 2) although our «hello world» contains 11 letters, our program didn’t crash anymore and our variable c hadn’t been overwritten.

Reference

Источник

Оцените статью
Adblock
detector