Click here to Skip to main content
15,886,078 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

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:

C++
int fileExists(TCHAR * file)
{
   WIN32_FIND_DATA FindFileData;
   HANDLE handle = FindFirstFile(file, &FindFileData) ;
   int found = handle != INVALID_HANDLE_VALUE;
   if(found) 
   {
       FindClose(&handle);
   }
   return found;
}


This code looks to see if a file exists without opening it.
 
Share this answer
 
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.

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

[/Update]
 
Share this answer
 
v2
Comments
Venkat Raghvan 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.).

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900