Click here to Skip to main content
11,505,486 members (58,668 online)
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 2: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 Sergey Alexandrovich Kryukov 532
1 F-ES Sitecore 380
2 Richard Deeming 270
3 CHill60 245
4 Richard MacCutchan 230
0 Sergey Alexandrovich Kryukov 1,067
1 Maciej Los 575
2 Peter Leow 540
3 F-ES Sitecore 525
4 DamithSL 470


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