C- programming: Reading filename from keyboard

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
10 replies · 11K views
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.. :(
 
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;
}
 
Oh - in general, gets is a BAD idea - it allows string overrun exploits. For your own code it is fine doing desktop programming.
 
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!