Home > Software engineering >  Check if file exists - C programming
Check if file exists - C programming

Time:02-14

I've had trouble trying to create this function that takes users input and checks if the file exists or not. I keep on getting warning messages (format specifies type 'char *' but the argument has type 'const char **') every time I try to run the code.

I've tried to declare the variable fileName in different ways but it still seems to not be working. So I'm curious to know if I'm using access wrong or if it's even possible to use when taking user input.

int readFunc(const char *fileName) {
    printf("Search for file: ");
    scanf("%s", &fileName);

    if(access(fileName, F_OK) == 0) {
        menuFunc();
    } else {
        printf("File doesn't exist!\n");
    }
}

CodePudding user response:

If the C programming language had a string data type, the following lines of code would be correct:

string fileName;
scanf("%s", &fileName);

However, the C programming language does not have a string data type, but strings must be stored in arrays of characters.

The char * data type does not hold a complete string, but it holds a "pointer" to an array. This means: The data type holds a reference to an array where the string is stored.

Let's say we use a self-written variant of scanf() named myScanf():

const char * fileName;
myScanf("%s", &fileName);

In this example the function myScanf() returns a "pointer" to a string. This means: The function stores the string in some array and then returns the reference ("pointer") to that array in the variable fileName.

The problem is: Because the function scanf() does not know which array should be used to store the string, you have to provide this array.

This means: scanf() does not return a pointer to an array (unlike "&d", which returns a number), but scanf() takes a pointer to an array (to the array where you want scanf() to store the string) as input argument:

int a;
char *b;
...
scanf("%d", &a); /* a is an output from scanf() */
scanf("%s", b); /* b is an input to scanf() */

However, the following line will also not work:

scanf("%s", fileName);

You tell scanf() to overwrite the array that has been passed as argument to the readFunc() function; and the const specifier says, that the function readFunc() must not overwrite this array!

You have to specify your own array where the file name is stored:

char fileName2[300]; /* Maximum 300-1 characters */
...
scanf("%s", fileName2);
...
access(fileName2, F_OK);

Note that C cannot really pass arrays to functions as arguments.

Instead, it automatically creates a "pointer" (a reference, data type char *) to the array if you write something like access(fileName2 ...).

  •  Tags:  
  • c
  • Related