Write a C program to attempt to open a file for reading If i
Write a C program to attempt to open a file for reading. If it can be opened, close it and return a 0. If it cannot be opened, return a 1 and quit. The filename should be an argument to your program. Use \"echo $?\" after running your program, to see the result.
Solution
Please find the below code:
#include <stdio.h>
int main(int argv,char* args[])
{
FILE *fptr;
fptr = fopen(args[1],\"r\");
if(fptr == NULL)
{
return 1;
}
fclose(fptr);
return 0;
}
Here we have main function which has the following two arguments:
1. argc -> It gives the total number of arguments
2. args -> it is character pointer for the argument.
For getting the Arguments we have to args parameter. So the argument we pass would be at the args[1]. Then we open the file in the read mode using fopen command passing the file pointer.
If the File pointer gets null from the fopen command means the file cannot be opened else we FILE datastructure in return of the fopen command.
so for the above condition we have kept an condition that if the fptr == NULL means the file can not be opened else the file can be opened an return 0.
