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; } |
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. |
Thanks
|
All times are GMT -5. The time now is 09:09 AM. |