Files

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

Files in C

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.

An example of a text file.


Every file has some name and
an extension. Here the name
of the file is Sample and
extension is .txt
Types of Files

Binary files Text files


 Binary files are mostly the Executable  Text files are the normal .txt files. You
files, compiled programs, graphic can easily create text files using any simple
(image) files, audio/video files in your text editors such as Notepad.
computer.  When you open those files, you'll see all
 Instead of storing the data in plain the contents within the file as plain text.
text, they store data in the binary form You can easily edit or delete the contents.
(0's and 1's).
 Appropriate software/programs are
required to interpret the data present in
these files.
Instead of giving input to the program through console I/O operations such as scanf()
and printf(), store all data into a file and design a C program to read this data as
input. Similarly instead of displaying the output data on the terminal design a C
program to write the output of the program into a file. This helps to store the data
permanently in files in the computers secondary memory and can be referred
whenever required.

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

Basic Operations on the file,


 Creating and Naming a file.
 Opening a file.
 Reading data from the file.
 Writing data to the file.
 Closing the file
1. Declaring a File pointer variable
 In order to perform any operations on the file we must first
have an access to the files location(address).
 This is done by creating a pointer pointing to the FILE
structure (defined in stdio.h). This is accomplished by declaring
a FILE pointer.
Syntax for declaring a FILE pointer:
FILE *file_pointer_name;
An Example,
FILE *fp;
2. Opening the file
 A file must be opened before data can be read from or
written to it.
 In order to open a file and associate it with a stream, the
fopen() function is used.
 fopen() function returns a pointer to the structure on
successful opening of the file and if it fails it returns NULL.
Syntax for opening a file: r for reading
w for writing
FILE *fp; a for appending
fp = fopen(“filename”,“mode”);
FILE *fp;
An example,
fp = fopen(“sample.txt”,“w”);
2. Opening the file
 If the file is in the current working directory, then just
name of the file is enough while opening it.
Example: fopen(“sample.txt”, “r”);
 However, full path of the files location should be given if
it is not in the current working directory.
Example: fopen(“D:\\Programs\\sample.txt”, “r”);
 As fopen() returns NULL if the file
does not exist, it’s the duty of
programmer to always check if the
file exists or no before proceeding
further.
An Example:
Different modes for opening a file
Mode Description

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.

Open for append.


a Data is added to the end of
the file.
If the file does not exist, a new file will be
created.

r+ Open for both reading and


writing.
If the file does not exist, fopen() returns NULL.

w+ Open for both reading and


writing.
If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

a+ Open for both reading and


appending.
If the file does not exist, it will be created.
3. Processing the file (reading/writing)
There are various functions available for reading data from the
file and writing data to the file.

Functions for reading data from Functions for writing data to a


a file: file:
 fgetc()  fputc()
 fgets()  fputs()
 fscanf()  fprintf()
 fread()  fwrite()
4. Closing the file
 To close the opened file, the fclose() function is used which
disconnects a file pointer from a file
 After fclose() function has disconnected the file pointer from the
file, the pointer can be used to access a different file.
 Along with closing the file it also flushes all the buffers that are
maintained for that file.

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);

The variable ch has


‘A’ that is written to
the student.txt file
Reading data from a file using fgets():
 fgets() function reads at most one less than the number of characters
specified by size from the given stream.
 fgets() terminates as soon as it encounters either a newline/EOF/or error.
Example:
Syntax:
FILE *fp;
char fgets(char *s, int size, FILE *stream); char s[10];
fp = fopen(“student.txt”, “r”);
fgets(s, 10, fp);

First 9-1 Characters are


read from the file
student.txt and stored in
string s, and with help of
printf() s is printed and
you can observe that only
Hello Al is printed living
the last ‘l’ because of size
given as 9.
Writing data to a file using fputs():
 fputs() function is used to write a line to a file.
 fputs() returns 0 on success or EOF in case of any error.
Example:
Syntax: FILE *fp;
int fputs(char *s, FILE *stream); char s[10]= “Hello All”;
fp = fopen(“student.txt”, “w”);
fputs(s, fp);

The string s is “Hello


All” which is written to
the file student.txt with
the help of fputs()
Reading data from a file using fscanf():
 fscanf() function is used to read formatted data from the file.
 fscanf() terminates as soon as it encounters either a newline/EOF/or error.
Syntax:
int fscanf(FILE *stream, “format specifiers”, variables);
Example:
fscanf(fp, “%d%s”, &rollno, name);

1 and Ravi is read from


student.txt file and
stored in rollno and
name variables
respectively and are
printed using printf().
Writing data to a file using fprintf():
 fprintf() function is used to write formatted data to a file.

Syntax:
int fprintf(FILE *stream, “format specifiers”, variables);
Example:
fprintf(fp, “%d%s”, &rollno, name);

The values of rollno


and name variables are
written to the file
student.txt.
Write a C program to read and print all the data present in the demo.txt file.

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy