Files
Files
Files
Why Files?
Till now, we were dealing with data associated with the programs
in the console/terminal with the help of console oriented I/O
functions such as printf() and scanf() functions.
This data can be an input to the program or it can be an output of
the program.
Handling data in the console becomes difficult as the size of the
data increases because in console oriented I/O operations the data
is lost as soon as the console/terminal is closed or the program
execution is completed or the computer is turned off.
Therefore, in order to retain such data instead of loosing it in the
terminal a FILE can be used.
What is a File?
A file is a place on the disk where a group of related data
is stored.
A file is a collection of data stored on a secondary
storage device such as hard disk.
Output
Input Program
Hello world!
Using Files in C
To use files in C, we must use the following steps,
1. Declare a File pointer variable
2. Open the file (in any one of the modes- r w a)
3. Process the file (read/write)
4. Close the file
r Opens the file for reading. If the file does not exist, fopen() returns NULL.
w Opens the file for writing. If the file exists, its contents are overwritten.
If the file does not exist, a file will be created.
Syntax:
fclose(FILE *fp);
Example, fclose(fp);
Reading data from a file using fgetc():
fgetc() is used to read one character at a time from a file.
fgetc() returns the character as an int or return EOF to indicate an error or
end of the file. Example:
Syntax: FILE *fp;
int fgetc(FILE *stream); char ch;
fp = fopen(“student.txt”, “r”);
ch = fgetc(fp);
H is read from
student.txt file
and stored in ch
Writing data to a file using fputc():
fputc() is used to write one character(a byte) to the file.
fputc() returns the character value that it has written on success or EOF in
case of error. Example:
Syntax: FILE *fp;
int fputc(int c, FILE *stream); char ch= ‘A’;
fp = fopen(“student.txt”, “w”);
fputc(ch, fp);
Syntax:
int fprintf(FILE *stream, “format specifiers”, variables);
Example:
fprintf(fp, “%d%s”, &rollno, name);
As we know fgetc()
reads one character at
a time from the file
wherever fp is pointing
to. So a loop is used to
repeatedly read the
characters one after
the other and printed
using printf()
Output:
Write a C program to copy the contents of one file to another file.
Write a C program to create a file named myfile and write content that the
user types from the keyboard till the user enters 0.
Output:
Write a C program to read the contents of the file hello.txt and print the following
details- No of words, No of characters, No of lines, No of whitespaces.
Write a C program that creates a file reading contents that the user types from the
keyboard till EOF. The text in this file must be in lowercase. There could be
multiple blanks in between some words. Create another file in which the same
content is copied in UPPERCASE and with only one blank in between the words
that contained multiple blanks.