Click here to Skip to main content
13,258,269 members (39,809 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I want to program that file name input that allow the user 3 chances to enter a valid file name. If a valid file name is not entered after 3 chances, terminate the program.
else print successful message
Posted 14-Mar-13 3:33am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

That usually depend on what you mean with 'valid filename', e.g. Should its path be formally correct? Should it be an existing file? Should it be a new file? ("Should we buy a new guitar?").
Depending on your needs you have to build your validation function (it might be very simple, e.g. just trying to open the file). Once you have the validation function you have only to keep track of failed attempts and close the program if this number becomes 3.

I would use
int i;
for (i=0; i<3; i++)
  printf("\n\nEnter filename :" );
  gets( fname );
  fp = fopen (fname, "r");
  if (fp)
  printf("Cannot open %s for reading \n", fname );
if ( ! fp ) return -1; // exit the program here
// fp is OK here, you may continue...

Sameer_awana 14-Mar-13 8:49am
Thanks,it's working!!
H.Brydon 14-Mar-13 17:16pm
This code has a bug in that you try to detect that the file exists by opening it, which might fail (eg. if another process has it open exclusively, file protection problem, etc.).
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Are you asking for code to check for a valid filename or that a particular filename exists already on the file system?

For the latter:

int fileExists(TCHAR * file)
   WIN32_FIND_DATA FindFileData;
   HANDLE handle = FindFirstFile(file, &FindFileData) ;
   int found = handle != INVALID_HANDLE_VALUE;
   return found;

This code looks to see if a file exists without opening it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.171114.1 | Last Updated 14 Mar 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100