In the earlier chapters we have seen that when we want to give Input or take Output in the program, we do it using consol. In this chapter we will learn to make Input or output using an external file in the C Program.
Following are the various operations we can perform on a file:
- Creation of a file
- Opening an existing file
- Reading from a file
- Writing data to the file
- Closing a file
In order to read or write using a file in C, we must open the file first using fopen(). In fopen() function, we provide the name of the file and the mode in which file must be opened. When an ‘r’ is used, the file is opened for reading, a ‘w’ is used to indicate a file to be used for writing and an ‘a’ indicates that you desire to append additional data to the data already in an existing file. The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard Output Device.
Reading from a text file
funny = fopen("README.TXT", "r");
if (fp == NULL)
printf("File doesn't exist\n");
c = getc(fp); /* get one character from the file */
putchar(c); /* display it on the monitor */
} while (c != EOF); /* repeat until EOF (end of file) */