0% found this document useful (0 votes)
139 views17 pages

Files in C

- Files in C are used to store data permanently even after program termination. There are two main types - text files (.txt) which store plain text, and binary files (.bin) which store data in 0s and 1s allowing for more efficient storage. - The main file operations in C are opening, reading, writing, and closing files. Files are opened using fopen() and closed with fclose(). Common functions to read and write files include fgets(), fputs(), fscanf(), fprintf(). - Examples show how to write a sentence to a file using fprintf(), and read the contents of that file using fscanf() to retrieve and print the stored text. Managing files

Uploaded by

Vani Balamurali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views17 pages

Files in C

- Files in C are used to store data permanently even after program termination. There are two main types - text files (.txt) which store plain text, and binary files (.bin) which store data in 0s and 1s allowing for more efficient storage. - The main file operations in C are opening, reading, writing, and closing files. Files are opened using fopen() and closed with fclose(). Common functions to read and write files include fgets(), fputs(), fscanf(), fprintf(). - Examples show how to write a sentence to a file using fprintf(), and read the contents of that file using fscanf() to retrieve and print the stored text. Managing files

Uploaded by

Vani Balamurali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Files in C

Introduction

A file represents a sequence of bytes, regardless of it being a


text file or a binary file.
C programming language provides access on high level
functions as well as low level (OS level) calls to handle file on
storage devices.
Why files are needed?
When a program is terminated, the entire data is lost. Storing
in a file will preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of
time to enter them all. However, if you have a file containing all
the data, you can easily access the contents of the file using
few commands in C.
You can easily move your data from one computer to another
without any changes.

Types of Files
When dealing with files, there are two types of files you should know
about:

Text files
Binary files

1. Text files
Text files are the normal .txt files that you can easily create using
Notepad or any simple text editors.
When you open those files, you'll see all the contents within the file
as plain text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and
provide least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form
(0's and 1's).
They can hold higher amount of data, are not readable easily and
provides a better security than text files.

File Operations
In C, you can perform four major operations on the file,
either text or binary:
Creating a new file
Opening an existing file
Closing a file
Reading from and writing information to a file
Working with files
When working with files, you need to declare a pointer of
type file.
This declaration is needed for communication between the
file and program.
FILE *fptr;

Opening a file
You can use the fopen( ) function to create a new file or to
open an existing file.
This call will initialize an object of the type FILE, which
contains all the information necessary to control the
stream.
The prototype of this function call is as follows
fptr = fopen( const char * filename, const char *
mode );
Here, filename is a string literal, which you will use to
name your file, and access mode can be to read, write,
append, or both read & write.
If you are going to handle binary files, then you will use
following access modes
"rb", "wb", "ab", "rb+", "wb+", "ab+"

Mode

Description

Opens an existing text file for reading purpose.

Opens a text file for writing. If it does not exist, then a


new file is created. Here your program will start writing
content from the beginning of the file.

Opens a text file for writing in appending mode. If it does


not exist, then a new file is created. Here your program
will start appending content in the existing file content.

r+

Opens a text file for both reading and writing.

w+

Opens a text file for both reading and writing. It first


truncates the file to zero length if it exists, otherwise
creates a file if it does not exist.

a+

Opens a text file for both reading and writing. It creates


the file if it does not exist. The reading will start from the
beginning but writing can only be appended.

Closing a File
To close a file, use the fclose( ) function.
The prototype of this function is
fclose( FILE *fptr );
The fclose(-) function returns zero on success, or EOF if
there is an error in closing the file.
This function actually flushes any data still pending in the
buffer to the file, closes the file, and releases any memory
used for the file.
The EOF is a constant defined in the header file stdio.h.

Writing a File
Following is the simplest function to write individual characters to a
stream
int fputc( int c, FILE *fptr );
The function fputc() writes the character value of the argument c
to the output stream referenced by fptr.
It returns the written character written on success otherwise EOF if
there is an error.
You can use the following functions to write a null-terminated string
to a stream
int fputs( const char *s, FILE *fptr );
The function fputs() writes the string s to the output stream
referenced by fptr.
It returns a non-negative value on success, otherwise EOF is
returned in case of any error.
You can use
int fprintf(FILE *fp,const char *format, ...)
function as well to write a string into a file

#include <stdio.h>
main()
{
FILE *fptr;
fptr = fopen(c:\\tmp\\test.txt", "w+");
fprintf(fptr, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fptr);
fclose(fptr);
}
Before executing this program we need to create a
directory by name tmp under C drive in the machine
When the above code is compiled and executed, it creates
a new file test.txt in tmp directory and writes two lines
using two different functions

Reading a File
Following is the simplest function to read a single character from a file
int fgetc( FILE * fptr );
The fgetc() function reads a character from the input file referenced by
fptr.
The return value is the character read, or in case of any error, it returns
EOF.
The following function allows to read a string from a stream
char *fgets( char *buf, int n, FILE *fptr );
The functions fgets() reads up to n-1 characters from the input stream
referenced by fptr.
It copies the read string into the buffer buf, appending a null character
to terminate the string.
If this function encounters a newline character '\n' or the end of the file
EOF before they have read the maximum number of characters, then it
returns only the characters read up to that point including the new line
character.
You can also use
int fscanf(FILE *fp, const char *format, ...)

function to read strings from a file, but it stops reading after


encountering the first space character

#include <stdio.h>
main()
{
FILE *fptr;
char buff[255];
if ((fptr = fopen("C:\\tmp\\test.txt","r")) == NULL){
printf("Error! opening file");
exit(0);
}
fscanf(fptr, "%s", buff);
printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fptr);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fptr);
printf("3: %s\n", buff );
fclose(fp);
}

When the above code is compiled and executed, it reads


the file created in the previous section and produces the
following result
1 : This
2: is testing for fprintf...
3: This is testing for fputs...

First, fscanf() read just This because after that, it


encountered a space, second call is for fgets() which reads
the remaining line till it encountered end of line.
Finally, the last call fgets() reads the second line
completely

Program to Write a Sentence to a File.


#include <stdio.h>
#include <stdlib.h>
int main()
{
char sentence[1000];
FILE *fptr; fptr = fopen("program.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(0);
}
printf("Enter a sentence:\n");
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}

After termination of this program, you can see a text file


program.txt created in the same location where this
program is located.
If you open and see the content, you can see the sentence
typed by you.
In this program, a file is opened using opening mode "w".
In this mode, if the file exists, its contents are overwritten
and if the file does not exist, it will be created.
Then, user is asked to enter a sentence.
This sentence will be stored in file program.txt using
fprintf() function.

Program to read the contents from a file


#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
exit(0);
}
fscanf(fptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}

If the file program.txt is not found, this program prints error


message.
If the file is found, the program saves the content of the file
to a string c until '\n' newline is encountered.
Suppose, the program.txt file contains following text.
C programming is awesome.
I love C programming.
How are you doing?
The output of the program will be:
Data from the file: C programming is awesome.

Programs on files

You might also like