2 Replies - 3167 Views - Last Post: 31 August 2014 - 04:57 AM Rate Topic: -----

#1 geekyandproud   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 31-August 14

Prompt User to Input File Name to Open

Posted 31 August 2014 - 03:38 AM

I'm trying to develop a programme which, amongst other things, prompts the user to enter the filename which is to be opened. This is what my code looks like currently:

char filename[20];
FILE *myfile;

    printf("Enter the full file name you would like to open:\n");
    scanf("%s", filename);
    myfile = fopen("filename", "r");
    if (myfile!=NULL)
        printf("File Found"); 
        printf("File Not Found"); 

However, this only ever returns File Not Found - the file is stored in the same directory as the program, and I have tried looking up this issue online, to no avail - please help?! I've just started programming in C, so forgive me if this is an amateurish question!

Is This A Good Question/Topic? 0
  • +

Replies To: Prompt User to Input File Name to Open

#2 jimblumberg   User is online

  • member icon

Reputation: 5521
  • View blog
  • Posts: 17,111
  • Joined: 25-December 09

Re: Prompt User to Input File Name to Open

Posted 31 August 2014 - 04:08 AM

What exactly are you entering for the filename?

How are you running this program? At the command line? Inside an IDE? Have you tried giving the complete path to the file?

When running the program from inside an IDE many times the file must be located in the directory where the project files are located, not necessarily where the executable is located.

Sometimes the easiest way to see what is happening is to create a file for output with a unique name, then locate that file using your operating system "find" functionality. Then place your input file in the same directory as that file.

And remember scanf() with the "%s" format specifier will not accept a value that contains any spaces. If your filename contains spaces you'll need to use something like fgets() (but don't forget to remove the new line character if present).


This post has been edited by jimblumberg: 31 August 2014 - 04:11 AM

Was This Post Helpful? 0
  • +
  • -

#3 Salem_c   User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 2167
  • View blog
  • Posts: 4,235
  • Joined: 30-May 10

Re: Prompt User to Input File Name to Open

Posted 31 August 2014 - 04:57 AM

> 07 myfile = fopen("filename", "r");
You're also trying to open filename literally called "filename", which has nothing to do with the variable of the same name, or indeed whatever you type in.

Also, if you're a windows user, make sure you turn OFF the windows explorer option called "hide extension of known file types". You may find your file is really called file.txt.txt
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1