Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - gets

Node:gets, Next:, Previous:Deprecated string input functions, Up:Deprecated string input functions



gets

If you want to read a string from standard input, you can use the gets function, the name of which stands for "get string". However, this function is deprecated -- that means it is obsolete and it is strongly suggested you do not use it -- because it is dangerous. It is dangerous because it provides no protection against overflowing the string into which it is saving data. Programs that use gets can actually be a security problem on your computer. Since it is sometimes used in older code (which is why the GNU C Library still provides it), we will examine it briefly; nevertheless, you should always use the function getline instead. (See getline.)

The gets function takes one parameter, the string in which to store the data read. It reads characters from standard input up to the next newline character (that is, when the user presses <RETURN>), discards the newline character, and copies the rest into the string passed to it. If there was no error, it returns the same string (as a return value, which may be discarded); otherwise, if there was an error, it returns a null pointer.

Here is a short code example that uses gets:

#include <stdio.h>

int main()
{
  char my_string[500];
  printf("Type something.\n");
  gets(my_string);
  printf ("You typed: %s\n", my_string);

  return 0;
}

If you attempt to compile the example above, it will compile and will run properly, but GCC will warn you against the use of a deprecated function, as follows:

/tmp/ccPW3krf.o: In function `main':
/tmp/ccPW3krf.o(.text+0x24): the `gets' function
     is dangerous and should not be used.

Remember! Never use this function in your own code. Always use getline instead.

 
 
  Published under free license. Design by Interspire