LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   fgets vs gets (https://www.linuxquestions.org/questions/programming-9/fgets-vs-gets-121501/)

cxel91a 12-01-2003 01:55 AM

fgets vs gets
 
Can someone explain why gets will work and not fgets. The output of fgets() shows the filename entered, but it will not open it.




#include<stdio.h>
#include<unistd.h>
#include<errno.h>

int main()
{
FILE* newFile;
char buffer[80];
char fileName[80];

printf("Enter a file to open: ");
fgets(fileName,80,stdin);

printf("%s",fileName);
newFile=fopen(fileName,"r");

if ( ! newFile) {
perror("NewFile error: ");
exit(1);
}

while ( fgets(buffer,80,newFile) != NULL) {
printf("%s",buffer);
}
fclose(newFile);
return 0;
}

worldmagic 12-01-2003 05:50 AM

From the manual page:

gets() reads a line from stdin into the buffer pointed to by s until
either a terminating newline or EOF, which it replaces with '\0'.

and

fgets() Reading stops after an EOF or a newline.
If a newline is read, it is stored into the buffer.

gets() doesnt include the newline (\n), but fgets include the \n in the string.
If you strip the \n character you can use fgets as in your example..

printf("Enter a file to open: ");
fgets(fileName,80,stdin);

fileName[strlen(fileName)-1] = '\0';
printf("Filename: <%s>",fileName);

Hope this helps.

cxel91a 12-01-2003 12:36 PM

Thanks


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