Computer Science, asked by lovishasharma9, 8 months ago

Which function does not exist in c language

Answers

Answered by amiteshkumar71
2

Answer:

Please make me at brainlist and follow me

Attachments:
Answered by Anonymous
6

Sometimes you want to check if a file exists before doing anything else such as backup, copy, modify or just read data from the file. However, C does not provide any built-in function to check if a file exists.

Fortunately, we can use other built-in functions to develop our own function check whether a file exists. There are several ways to accomplish this task.

C file exists function using fopen() function

In the first approach, we will try to read the data from the file using the fopen() function. If we can read data from the file, it means the file exists otherwise it does not. The following is the C file exists function to check if a file exists using the fopen() function.

1

2

3

4

5

6

7

8

9

10

11

12

13

/*

* Check if a file exist using fopen() function

* return 1 if the file exist otherwise return 0

*/

int cfileexists(const char * filename){

/* try to open file to read */

FILE *file;

if (file = fopen(filename, "r")){

fclose(file);

return 1;

}

return 0;

}

The function accepts a file name and returns 1 if the file exists, otherwise, it returns 0.

C file exists checking function using stat() function

In the second approach, instead of reading data from a file, we read the file’s attributes using the stat() function. The stat() function return zero (0) if the operation is successful, otherwise if the file does not exist, it returns -1.

We can make use of the stat() function to check if a file exists as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

#include <sys/stat.h>

/*

* Check if a file exist using stat() function

* return 1 if the file exist otherwise return 0

*/

int cfileexists(const char* filename){

struct stat buffer;

int exist = stat(filename,&buffer);

if(exist == 0)

return 1;

else // -1

return 0;

}Testing C file exists checking function

Let’s test our C file exist checking function. First, you need to create a file in the C:\temp directory called test.txt or whatever name you like. Then you can use the following code snippet to test the function:

1

2

3

4

5

6

char* filename = "C:\\temp\\test.txt";

int exist = cfileexists(filename);

if(exist)

printf("File %s exist",filename);

else

printf("File %s does not exist",filename);

In this tutorial, you have learned how to use standard C functions to develop a C file exists checking functions that check if a file exists.

Similar questions