C Programming - Input / Output - Discussion

4. 

Point out the error in the program?

#include<stdio.h>

/* Assume there is a file called 'file.c' in c:\tc directory. */
int main()
{
    FILE *fp;
    fp=fopen("c:\tc\file.c", "r");    
    if(!fp) 
      printf("Unable to open file.");        

    fclose(fp);
    return 0;
}

[A]. No error, No output.
[B]. Program crashes at run time.
[C]. Output: Unable to open file.
[D]. None of above

Answer: Option C

Explanation:

The path of file name must be given as "c:\\tc\file.c"

Vishal said: (Dec 19, 2013)  
It crashes at run time. As the fp is NULL and its being passed to fclose.

Pravin said: (Feb 28, 2014)  
If we write the path as given in explanation then option A will be the ans?

Bhushan said: (Nov 1, 2015)  
The program running successfully. The explanation was given wrong.

Vijay said: (Mar 15, 2016)  
Why should we give path name as c:\\tc\file.c?

Rohan said: (Jul 1, 2016)  
Program running successfully. There is no problem with the syntax of given path and extension but I don't logic of this if (! fp) ;.

Apoorva said: (Jul 31, 2016)  
c:\ tc\file.c is incorrect way of reading because when drive is specified like c,d etc .file path should be c:\\tc\file.c.
So, fp contain 0 value. if(!fp) means complementing fp content .if (condition) if statement falls only for 0.

Here if(!fp) becomes true so "Unable to open file" will be printed.

Shree said: (Jun 13, 2017)  
The Application will crash as mentioned by Visual.

int main()
{
FILE *fp;
fp = fopen("c:\tc\file.c", "r");
if(!fp)
printf("Unable to open file.");
else
fclose(fp);
return 0;
}

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.