LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-01-2003, 01:55 AM   #1
cxel91a
Member
 
Registered: May 2001
Posts: 61

Rep: Reputation: 15
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;
}
 
Old 12-01-2003, 05:50 AM   #2
worldmagic
Member
 
Registered: Oct 2003
Location: Europe/Sweden
Distribution: RedHat
Posts: 78

Rep: Reputation: 15
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.
 
Old 12-01-2003, 12:36 PM   #3
cxel91a
Member
 
Registered: May 2001
Posts: 61

Original Poster
Rep: Reputation: 15
Thanks
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
php fgets really slow pasholy2001 Programming 0 04-22-2005 02:17 AM
reading in string with fgets bostonbanana Programming 4 12-12-2004 02:10 PM
Is fgets functions secure? mullog Programming 2 10-02-2004 01:22 PM
fgets() problems in C AMMullan Programming 4 03-12-2004 04:39 AM
fgets h/w Programming 23 12-21-2003 06:20 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:29 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration