Enter custom file name to be read?

37,506

Solution 1

The scanf statement will try to store the filename entered as input into the memory, starting from the address passed as its 2nd argument. So you have to allocate/reserve some memory and pass its address to scanf.

As you have not mentioned the type of fname, let me list the possibilities and then answer you.

  1. char fname;

The 2nd argument of scanf and the 1st argument of fopen, both need to be char *. So, passing address of fname or &fname is valid. But it has a problem.

When you declare 'char fname' you are reserving memory for only 1 char. When scanf tries to store the input filename, it will have to write more than 1 char. So eventually you end up overwriting some other memory.

  1. char *fname;

In this case pass fname to both scanf and fopen, instead of '&fname'. But you have to allocate some memory (e.g. using malloc), before using fname. Otherwise fname will contain some garbage address and scanf will try to overwrite some random memory.

So either declare fname as char fname[N] or char *fname = malloc(N+1); (where N is the maximum possible length of filename you would be entering).

And then, pass fname to both scanf and fopen as follows:

scanf("%s",fname);

inputf = fopen(fname,"w");

Solution 2

Defining fname as a char array, and assuming you expect the filename (without extension) as input (which means you need to append the extension to it):

char fname[128];
printf("Enter .txt file name\n");
scanf("%123s",fname);
strcat(fname,".txt");
FILE *inputf;
inputf=fopen(fname,"w");

Note that an input length check is added to avoid buffer overflow errors in scanf.

Share:
37,506
NLed
Author by

NLed

Updated on June 21, 2020

Comments

  • NLed
    NLed almost 4 years

    I want to allow users to type the name of any .txt file to be read/written.

    This is my code :

      printf("Enter .txt file name\n");
      scanf("%s",&fname);
      FILE *inputf;
      inputf=fopen(&fname,"w");
    

    Problem is this method does not work (having &fname) as a parameter.

    I can imagine its because C needs "filename.txt" for it work ... even if I enter for example : "custom.txt", the program returns an error of "Storage block not big enough for this operation"

    What is the correct method to accomplish this ?

    Im using C and im pretty much using basic commands .. (not too advanced)

    Thanks alot !!!