C- programming: Reading filename from keyboard

malawi_glenn
Science Advisor
Messages
6,735
Reaction score
2,437
[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.. :(
 
Technology 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.
 
gets and fgets are not the same thing.
 
what is desktop programming?
 
that fgets and gets is not the same thing i know :-)
 
  • #10
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.
 
  • #11
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!
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
5
Views
2K
Replies
14
Views
4K
  • · Replies 19 ·
Replies
19
Views
2K
Replies
4
Views
3K
Replies
7
Views
2K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K