Unit 6.2
Unit 6.2
1 1
FILES:
A file is an external collection of related data treated as a unit.
Each file ends with an end of file (EOF) at a specified byte number,
recorded in file structure.
A file must first be opened properly before it can be accessed for reading
or writing. When a file is opened an object (buffer) is created and a stream
is associated with the object.
3 3
FILE NAME:
Every operating system uses a set of rules for naming its files.
The file name may contain two parts, a primary name and an
optional period with extension.
Example: input.txt
program.c
4 4
FILE INFORMATION TABLE:
The stdio.h header file defines this file structure; its name is FILE.
5 5
STREAM:
A stream is a source or destination of the data, it is associated with a
physical device such as terminals (keyboard, monitor) or with a file
stored in memory.
The first, stdin, points to the standard input stream which is normally
connected to the keyboard.
The third, points to the standard error stream which is also normally
connected to the monitor.
8 8
STREAM FILE PROCESSING:
9 9
Creating a Stream:
We can create a stream when we declare it.
The FILE type is a structure that contains the information needed for
reading and writing a file and spData is a pointer to the stream.
Opening a File:
Once stream has been created, we can ready to associate the stream to a
file. This is done through open function.
When the file is opened, the stream and the file are associated with each
other.
It does two things: First, it makes the connection between the physical
file and the file stream in the program.
To open a file, we need to specify the physical filename and its mode.
11 11
The file mode is a string that tells C compiler how we intend to use the
file: reading, writing or append.
The address of the file structure that contains the file information is
returned by fopen.
The actual contents of the FILE are hidden from our view.
All we need to know is that we can store the address of the file structure
and use it to read or write the file.
Once the files are open, they stay open until you close them or end the
program.
12 12
File Mode:When we open a file, we explicitly define its mode.
The mode shows how we will use the file: for reading, for writing, or for
appending.
When a file is opened in this mode, the file marker is positioned at the
beginning of the file (first character).
The file marker is a logical element in the file structure that keeps track of
our current position in the file.
The file must already exist: if it does not, NULL is returned as an error.
If we try to write a file opened in read mode, we get an error message.
If it is already exists, it is opened and all its data are erased; the file
marker is positioned at the beginning of the file (first character).
14 14
“a” (append mode):
The append mode (a) also opens an existing file for writing.
Instead of creating a new file, however, the writing starts after the last
character; that is new data is added, or appended, at the end of the file.
If the file doesn’t exist, it is created and opened. In this case, the writing
will start at the beginning of the file.
15 15
“w+” (write and read) mode:
In this mode a file is opened for both writing and reading the data.
If a file already exists its contents are erased. If a file does not exist then
new file created.
Syntax: fp=fopen (“filename”,”w+”);
16 16
File Modes
17
File Close (fclose):
Closing a file ensures that all outstanding information associated with the
file is flushed out from the buffers and all links to the file are broken.
Another instance where we have to close a file is to reopen the same file
in a different mode.
Once a file is closed, its file pointer can be reused for another file.
18 18
STANDARD LIBRARY I/O FUNCTIONS:
19 19
20 20
Operations on Files:
21
FORMATED I/O FUNCTIONS:
These two functions can be used only with the keyboard and
monitor.
22 22
Reading from Files: fscanf ()
It is used to read data from a user-specified stream.
The first argument is the stream pointer, it is the pointer to the streams
that has been declared and associated with a text file. Remaining is same
as scanf function arguments.
The fscanf function would read values from the file "pointed" to by fptr1
and assign those values to a and b.
23 23
The only difference between scanf and fscanf is that scanf reads data
from the stdin (input stream) and fscanf reads input from a user specified
stream(stdin or file).
The following example illustrates how to read data from keyboard using
fscanf,
fscanf (stdin,”%d”, &a);
End of File:
The end-of-file indicator informs the program when there are no more
data (no more bytes) to be processed.
24 24
Writing to Files: fprintf ()
It can handle a group of mixed data simultaneously.
The first argument of these functions is a file pointer which specifies the
file to be used.
Where stream_pointer is a file pointer associated with a file that has been
opened for writing.
The format string contains output specifications for the items in the list.
25 25
The following example illustrates the use of an Output stream.
int a = 5, b = 20;
FILE *fptr2;
fptr2 = fopen (“results", "w”);
fprintf (fptr2, "%d %d\n", a, b) ;
The fprintf functions would write the values stored in a and b to the file
"pointed" to by fptr2.
fprintf function works like printf except that it specifies the file in which
the data will be displayed.
The file can be standard output (stdout) or standard error (stderr) also.
Example,
fprintf (stdout,”%d”,45); //displays 45 on Monitor.
26 26
//Program to perform addition of two numbers using fscanf and fprintf.
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp1, *fp2;
int a,b,c;
fp1 = fopen(“myfile”,”r”);
fscanf(fp1,”%d%d”,&a,&b);
c=a+b;
fp2 = fopen(“output”,”w”);
fprintf(fp2, “sum=%d\n”, c);
fclose(fp2);
fclose(fp1);
}
27
//Program to copy contents of one file another file using fscanf and fprintf.
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp1, *fp2;
char ch;;
fp1 = fopen(“input.txt”,”r”);
fp2= fopen(“output.txt”,”w”);
while((fscanf(fp1,”%c”,&ch)) == 1)
fprintf(fp2, “%c”, ch);
fclose(fp1);
fclose(fp2);
}
28
CHARACTER I/O FUNCTIONS:
Character input functions read one character at a time from a text stream.
Character output functions write one character at the time to a text stream.
Character I/O
Here, we can use a more general set of functions that can be used with
both the standard streams and a file.
When used with a terminal device, the streams are declared and opened by
the system, the standard input stream (stdin) for the keyword and standard
output stream (stdout) for the monitor.
When used with a file, we need to explicitly declare the stream, it is our
responsibility to open the stream and associate with the file.
31 31
Read a character: getc () and fgetc ()
The getc functions read the next character from the stream, which can be
a user-defined stream or stdin, and converts it in to an integer.
This function has one argument which is the file pointer declared as FILE
or stdin (in case of standard input stream).
If the read detects an end of file, the function returns EOF, EOF is also
returned if any error occurs.
Syntax:
int getc (FILE *fpIn); or int getc(stdin);
int fgetc (FILE *fpIn); or int fgetc(stdin);
32 32
Write a Character: putc () and fputc ()
The putc function writes a character to the stream which can be a user-
defined stream, stdout, or stderr.
The first parameter is the character to be written and the second parameter
is the file.
If the character is successfully written, the function returns it. If any error
occurs, it returns EOF.
Syntax:
int putc (char, *fp);
int fputc (char, *fp); 33 33
/*Program to copy content of one file to another file using getc/putc*/
#include<stdio.h>
#include<stdlib.h>
main()
{
char ch=' ';
FILE *fp1,*fp2;
fp1=fopen("file1.c","r");
fp2=fopen("file2.c",”w");
if(fp1)
{
while((ch=getc(fp1))!=EOF)
{
putc(ch,fp2);
}
}
else
printf("\n File1 doesnot exists");
fcloseall();
}
/*Program to append one file to another file using getc/putc*/
#include<stdio.h>
void main()
{
char ch=' ';
FILE *fp1,*fp2;
fp1=fopen("file1.c","r");
fp2=fopen("file2.c",”a");
if(fp1) {
while((ch=getc(fp1))!=EOF)
{
putc(ch,fp2);
}
}
else
printf("\n File1 doesnot exists");
fcloseall();
}
LINE INPUT/OUTPUT
fgets() function
fgets() function is used to read string(array of characters) from the file.
The fputs() function takes two arguments, first is the string to be written to
the file and second is the file pointer where the string will be written. 36 36
/*Program to copy content of one file to another file using fgets /fputs*/
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp1,*fp2;
char str[80];
fp1=fopen("file1.c","r");
fp2=fopen("file2.c",”w");
if(fp1) {
while((fgets(str,80,fp1))!=NULL)
{
fputs(str,fp2);
}
}
else
printf("\n File1 doesnot exists");
fcloseall();
}
TEXT FILES AND BINARY FILES:
Text File: It is a file in which data are stored using only characters; a text file is
written using text stream.
Non-character data types are converted to a sequence of characters before they
are stored in the file.
In the text format, data are organized into lines, terminated by newline character.
The text files are in human readable form and they can be created and read
using any text editor.
Text files are read and written using input / output functions that convert
characters to data types: scanf and printf, getchar and putchar, fgets and
fputs.
Binary files are read and written using binary streams known as block input /
output functions.
40
Opening Binary Files
The basic operation is unchanged for binary files, only the mode changes.
Just like text files, binary files must be closed when they are not needed
anymore using fclose ().
Mode Meaning
This mode opens a binary file in write mode.
wb
Example: fp=fopen (“data.dat”,”wb”);
This mode opens a binary file in read mode.
rb
Example: fp=fopen (“data.dat”,”rb”);
This mode opens a binary file in append mode.
ab
Example: fp=fopen (“data.dat”,”ab”);
This mode opens/creates a binary file in write and read mode.
w+b
Example: fp=fopen (“data.dat”,”w+b”);
This mode opens a pre-existing binary file in read and write mode.
r+b
Example: fp=fopen (“data.dat”,”r+b”);
This mode opens/creates a binary file in append mode.
a+b
Example: fp=fopen (“data.dat”,”a+b”);
41
Binary Modes of Opened File
Opening Text / Binary Files:
C language uses the block input and output functions to read and write
data to binary files.
As we know that data are stored in memory in the form of 0’s and 1’s.
When we read and write the binary files, the data are transferred just as
they are found in memory and hence there are no format conversions.
The block read function is file read(fread) and the block write function is
file write (fwrite).
43 43
File Read: fread ()
It reads a specified number of bytes from a binary file and places them into
memory at the specified location.
For this purpose, it is required to allocate the sufficient memory and address of
the first byte is stored in pInArea.
The next two elements, elementSize and count, are multiplied to determine how
much data are to be transferred.
The size is normally specified using the sizeof operator and the count is normally
one when reading structures.
The last argument is the pointer to the file we want to read from.
This function returns the number of items read. If no items have been read or
when error has occurred or EOF encountered, the function returns 0. 44 44
Below is an example of a file read that reads data into an array of
integers. When fread is called, it transfers the next three integers
from the file to the array, inArea.
The parameters for file write correspond exactly to the parameters for the file
read function.
Example for file write operation:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main() {
FILE *fp;
char str[30],rev[30];
int n,j,i;
printf("\nEnter the num of character u want reverse:");
scanf("%d",&n);
fp=fopen("file3.c","r+b");
fread(str,sizeof(char),n,fp);
for(i=0,j=n-1;i<n;i++,j--) {
rev[i]=str[j];
}
rev[i]=‘\0’;
rewind(fp);
fwrite(rev,sizeof(char),n,fp);
fcloseall();
}
Command line arguments
• Passing parameters to the main function is called command
line arguments.
• It is also supplying the parameters to a program when the
program is running.
• If we want to copying the one file to another file use the
command as
c> ./a.out abc.data xyz.data.
• Main function also takes two arguments called argc and
argv the information contained in the command line is
passed on to the program through these arguments.
• argc- no of arguments passing to a program when the
program is running.
• argv()- it is an array of pointers to strings.
• When the program is executed, the strings on the command
line are passed to main()
• Ex- ./a.out abc.data xyx.data
Then
argc would contains 3
argv[0]- base address of the string “./a.out”
argv[1]- base address of the string “abc.data”
argv[2]- base address of the string “xyz.data”.
/*Program to copy the contents of one file to another file using command line
arguments*/
putc(ch,fpt2);
}
}
else
printf("\n File does not exists");
fcloseall();
}
Rewind File (rewind):
It simply sets the file position indicator to the beginning of the file.
It helps us in reading a file more than once, without having to close and open the
file.
A common use of the rewind function is to change a work file from a write state
to a read state.
Rewind File 51
Current Location (ftell):
It reports the current position of the file marker in the file, relative to the
beginning of the file.
It measures the position in the file by the number of bytes, relative to zero, from
the beginning of the file.
Syntax: long int ftell(FILE *stream);
It also returns the number of bytes from the beginning of the file.
The offset specifies the number of positions to be moved from the location
specified by position.
If we attempt to move the file pointer beyond the file boundaries, an error occurs
and fseek returns -1.
53
Operations of the fseek function
Statement Meaning
fseek(fp,0L,0); Go to the beginning.
fseek(fp,0L,1); Stay at the current position.
fseek(fp,0L,2); Go to the end of the file, past the last character
of the file.
fseek(fp,m,0) Move to (m+1)th byte in the file.
fseek(fp,m,1); Go forward by m bytes.
fseek(fp,-m,1); Go backward by m bytes from the current
position.
fseek(fp,-m,2); Go backward by m bytes from the end.
(positions the file to the character from the end.)
#include<stdio.h> //Program to demonstrate file positioning
functions.
main(){
FILE *fp;
char arr[30]; int i = 0; long int n;
fp = fopen("input.txt", "r");
n = ftell(fp);
printf("\nThe current posiotion of file marker=%d",n);
fseek(fp,-5,2); //go backward by 5 bytes from the end
n = ftell(fp);
printf("\nThe current posiotion of file marker=%d",n);
printf("\nCharacters read from file are:");
for(i = 0; i < 5; i++) {
arr[i] = fgetc(fp); rewind(fp); //reset offset to beginning
fputc(arr[i],fp); n = ftell(fp);
printf("%c",arr[i]); printf("\nThe current posiotion of file marker=%d",n);
} fseek(fp,5,1);
printf("\nCharacters read from file are:");
for(i = 0; i < 5; i++) {
arr[i] = fgetc(fp);
fputc(arr[i],fp);
printf("%c",arr[i]);
}
}
Different types of files to opened to write the contents
56
I/O Function used in FILES
• fopen() : Create or open a file for reading or writing.
• fclose() : Close a file after reading or writing it.
• fseek() : Move (Seek) to a certain location in a file.
• ftell() : Returns the current position of the file pointer.
• rewind() : Rewind a file back to its beginning and leave it open.
• fprintf() : Formatted write.
• fscanf() : Formatted read.
• fwrite() : Unformatted write. (The block read and write functions.)
• fread() : Unformatted read.
• putc() : Write a single byte to a file.
• getc() : Read a single byte from a file.
• fgets() : To read one line from a file at a time.
• fputs() : To write one line to a file at a time.
• fcloseall() : To close all opened files in a program
57
1. writing the data into the file
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("file.txt","w"); // open a file in write mode
printf("\nEnter data to be stored in to the file:");
while((ch=getchar())!=EOF) // writing the data into the file
fputc(ch,fp);
fclose(fp);
return 0;
}
58
2. To Read a file contents and print on the screen
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *fp;
fp = fopen(“abc.txt”,"r"); // open a file in read mode
if( fp == NULL )
{ printf("Error while opening the file.\n"); }
else
{
printf("The contents of file are :\n", );
while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
}
return 0;
} 59
3.1 copy the data from one file to another file(using fgetc,fputc)
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("file.txt",”r"); // open a file in read mode
fp2=fopen(“copy.txt”,”w”);
while((ch=fgetc(fp1))!=EOF) // writing the data into the file
fputc(ch,fp2);
fclose(fp);
return 0;
}
60
3.2 copy content of one file to another file using fgets /fputs
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp1,*fp2;
char str[80];
fp1=fopen("file1.c","r");
fp2=fopen("file2.c",”w");
if(fp1) {
while((fgets(str,80,fp1))!=NULL)
{
fputs(str,fp2);
}
}
else
printf("\n File1 doesnot exists");
fcloseall();
}
3.3 copy the contents of one file to another file using command
line arguments
#include<stdio.h>
#include<stdlib.h>
main(int argc,char *argv[]) {
FILE *fpt1,*fpt2;
char ch;
fpt1=fopen(argv[1],"r");
fpt2=fopen(argv[2],"w");
if(fpt1)
{
while(ch!=EOF) {
ch=getc(fpt1);
putc(ch,fpt2);
}
}
else
printf("\n File does not exists");
fcloseall();
}
3.4 copy the contents of one file to another file (read file names from keyboard)
#include<stdio.h> #include<stdlib.h>
void main()
{
FILE *fp1,*fp2;
char str1[30],str2[30],ch=‘ ‘;
printf(“enter source file name”);
scanf(“%s”,str1);
printf(“enter destination name”);
scanf(“%s”,str2);
fp1=fopen(str1,"r");
fp2=fopen(str2,"w");
if(fp1)
{
while(ch!=EOF) {
ch=getc(fp1);
putc(ch,fp2); }
}
else
printf("\n File does not exists");
fcloseall();
}
3.4 copy the contents of one file to another file (read file names from keyboard)
#include<stdio.h> #include<stdlib.h>
void main()
{
FILE *fp1,*fp2;
char str1[30],str2[30],ch=‘ ‘;
printf(“enter source file name”);
scanf(“%s”,str1);
printf(“enter destination name”);
scanf(“%s”,str2);
fp1=fopen(str1,"r");
fp2=fopen(str2,"w");
if(fp1)
{
while(ch!=EOF) {
ch=getc(fp1);
putc(ch,fp2); }
}
else
printf("\n File does not exists");
fcloseall();
}
4. Write a program to append file to another file
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen(“biodata.txt”,”a");
fp2=fopen(“marks.txt”,”r");
if(fp2)
{
while((ch=fgetc(fp2))!=EOF) {
fputc(ch,fp1); }
}
else
printf("\n File does not exists");
fcloseall();
}