C- programming: Reading filename from keyboard

AI Thread Summary
The discussion revolves around a C programming issue where a user is trying to open a file by entering its filename via keyboard input. The initial code fails because it does not handle the newline character returned by fgets, which is included in the filename string. A solution is provided that involves using strchr to remove the newline character before attempting to open the file. The conversation touches on the differences between fgets and gets, with a warning against using gets due to security risks like buffer overflows. The user expresses a desire to learn C programming, having a strong background in Java, and is working on a school project related to C. The discussion highlights the importance of proper string handling in file operations in C.
malawi_glenn
Science Advisor
Messages
6,735
Reaction score
2,432
[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!
 
Back
Top