Reading filename from keyboard with fgets in C

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
10 replies · 11K views
Science Advisor
Messages
6,735
Reaction score
2,438
[SOLVED] C- programming: Reading filename from keyboard

Hi!

I am trying to write a small program for open a file by entering filename with keyboard, but it does not work. Why?


int main(){


FILE *fp;


printf("Give filename ");

char str[100], *s;

s = fgets(str, 100 , stdin);

printf("\n");

fp = fopen(str, "r");

-----------

No file opens.. :(
 
Physics news on Phys.org
try:
Code:
#include <stdio.h>
#include <string.h>

int main()
{
   FILE *fp=NULL;;
   char str[100]={0x0};
   char *s=NULL;;

   printf("Give filename ");
   s=fgets(str, 100 , stdin);
   s=strchr(str,'\n');
   if(s!=NULL) *s=0x0;
   fp = fopen(str, "r");
   printf("%s open = ", str);
   if(fp!=NULL)
     printf("success\n");
   else
     printf("failure");
   fclose(fp);
   return 0;
}
 
I tried:

printf("Give filename ");

gets(filename);


fp = fopen(filename, "r");

-------

and it worked.
 
fgets returns the trailing \n which is not part of the filename.
 
jim mcnamara said:
fgets returns the trailing \n which is not part of the filename.

ok? but it worked
 
Oh - in general, gets is a BAD idea - it allows string overrun exploits. For your own code it is fine doing desktop programming.
 
that fgets and gets is not the same thing i know :-)
 
desktop programming - writing code for personal use in your profession. Also called 'skunkworks' coding. So if you play with quantum gravity, you might write some quick and dirty Mathematica routines to do a quick analysis. You probably would not consider it suitable for a publication.
 
yeah now I see. This is just for personal use, I want to learn C. Iknow Java very good, and want to do C++, but thinks is funnier to go to basics. Also we have a C-programming project in school, and I just thinks C is very cool. After this I will try Fortran.

thanx for your help!