Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C
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
good
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.
 
[Update]
I would use
  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]
  Permalink  
v2
Comments
Sameer_awana at 14-Mar-13 8:49am
   
Thanks,it's working!!
H.Brydon at 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
good
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;
   if(found) 
   {
       FindClose(&handle);
   }
   return found;
}
 
This code looks to see if a file exists without opening it.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 515
1 Maciej Los 290
2 Richard MacCutchan 265
3 BillWoodruff 235
4 Suraj Sahoo | Coding Passion 175
0 OriginalGriff 8,804
1 Sergey Alexandrovich Kryukov 7,457
2 DamithSL 5,689
3 Maciej Los 5,279
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web03 | 2.8.1411028.1 | Last Updated 14 Mar 2013
Copyright © CodeProject, 1999-2014
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