-   Programming (
-   -   gets library function in C (

reddazz 03-26-2005 10:28 PM

gets library function in C
I've been messing around with some C code and when I use the "gets function", I get the following error,


: warning: the `gets' function is dangerous and should not be used.
An example from the book I am using is below. How would I rewrite that code so that it doesn't use "gets".


#include <stdio.h>
#include <string.h>
int main (void)
        char buffer [256];
        printf ("Enter your name and press <ENTER>:\n");
        gets (buffer);
        printf ("Your name has %d characters and spaces!\n", strlen (buffer));
        return 0;

randyding 03-26-2005 11:03 PM

gets does not protect against buffer overflow, which is why its complaining.
Instead use
fgets will leave the end-of-line char on the of the buffer.
I always use this loop to remove it, this loop works on Windows and Linux.
The difference is that windows appends cr-lf and linux just lf.

char buffer[256];
char *p;
if (fgets(buffer,sizeof(buffer),stdin)) {
    while (p>buffer && *(p-1)<=' ') *(--p)='\0';

reddazz 03-26-2005 11:36 PM

Right, so I can use fgets. The syntax for "fgets" seems to be different to that of "gets" so I'll read up on it before trying your method and post some feedback later.

nixcraft 03-27-2005 03:04 AM

Yes use fgets is better choice

All times are GMT -5. The time now is 09:31 AM.