Program 202:
Output:
Store both text file and program in same folder.Here I named text file as file123.txt
#include<stdio.h> #include<stdlib.h> main () { FILE *file; char c; file=fopen("file123.txt","r"); while(1) { if(file==NULL) { printf("File Not Found\n"); exit(0); } else { c=fgetc(file); if(c==EOF) { break; } printf("%c",c); } } fclose(file); }Explanation:
- Declaring file which is FILE pointer and using fopen to open the file with read mode
while(1) { if(file==NULL) { printf("File Not Found\n"); exit(0); } else { c=fgetc(file); if(c==EOF) { break; } printf("%c",c); } }
If file123.txt doesnot exist in the expected location in our local machine/pc then file variable will be null(null means nothing or empty in coding).- If file==null we are printing File not found
- If there is file then while loop continuosly iterate by retrieving character by character using fgetc(file) which will retrieve one character at a time and print that character on console using printf("%c",c);
- If we reach End of the File then fgetc returns EOF to file pointer then we will break our loop and come out of it
- Finally, we should close/terminate the file that is opened using fclose
Output:
Store both text file and program in same folder.Here I named text file as file123.txt