user3623727
user3623727

Reputation: 7

How to input the name of the file you want to open?

I know that code will not run but how can i fix this? ( I am new to c)

  char name[20]  
  printf("Ender the name of text file you want to open ex: word.txt");
  scanf("%s", name);
  ptr = fopen("name", "r"); // There is the problem

Upvotes: 0

Views: 86

Answers (4)

Rahul
Rahul

Reputation: 170

char name[20];  //Missed the semi colon
printf("Ender the name of text file you want to open ex: word.txt");
scanf("%s", name);
ptr = fopen(name, "r"); // Remove the string literal. 

Using "name" means you are looking for a file named "name" in your directory to open. If you use name instead (no quotes) then you are looking for the string literal that is stored in the variable named name.

Upvotes: 0

barak manos
barak manos

Reputation: 30136

By calling fopen("name","r"), you are attempting to open a file called "name" for reading.


Assuming that you have FILE* ptr declared somewhere up there...

Change this:

ptr = fopen("name","r");

To this:

ptr = fopen(name,"r");

Upvotes: 2

kebs
kebs

Reputation: 6707

For file I/O, you need a FILE object, hence the code would be:

FILE* ptr;
ptr = fopen( name, "r" );

and also check the return value, that will be NULL in case of failure.

Check out this link for more details.

Upvotes: 0

phyrrus9
phyrrus9

Reputation: 1467

Just simply pass name instead:

if ((ptr = fopen(name, "r")) == NULL)
{
    fprintf(stderr, "We have a problem!\n");
    return -1;
}

Also, do some error checking to ensure it is really open.

Upvotes: 0

Related Questions