I am trying to create a function which takes a file name from the user and checks if it exists, as long as it does not exist I wish to re-ask the user to input a file until it finds a file that does exist. Finally, I wish to return the name of that file to the main in order to use in a different function.
I've created a function which I thought would work but it seems that I may have a problem with calling the variable and not inputting the file name directly. (I'm not positive that that is the issue).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char* fileCheck();
char* fileCheck()
{
char* fileName;
printf("Please enter a file name: ");
gets(fileName);
while (access(fileName, F_OK) == -1)
{
printf("The File %s was not Found\nPlease enter a new file name: ", fileName);
gets(fileName);
}
return fileName;
}
int main (void)
{
fileCheck();
return 0;
}
I expect the output of the function to be the valid (existing) file name. In actuality I am receiving a garbage number exit code.