Module 5
Module 5
Module 5
Topics
• Files: Introduction to Files
• Using Files in C
• Read Data from Files
• Writing Data to Files
• Example Programs.
Introduction to Files
• A file is a collection of data stored on a secondary storage device like
hard disk.
• Broadly speaking, a file is basically used because real-life applications
involve large amounts of data and in such applications the console-
oriented I/O operations pose two major problems:
⮚First, it becomes cumbersome and time-consuming to handle huge
amount of data through terminals.
⮚Second, when doing I/O terminal, the entire data is lost when either
the program is terminated or computer is turned off. Therefore, it
becomes necessary to store data on a permanent storage device(eg:
hard disk) and read whenever required, without destroying the data.
The three standard streams in C are:
• Standard input(stdin)
• Standard output(stdout)
• Standard error(stderr)
Streams in C
• Standard Input(stdin): standard input or the stream from which the program receives its data.
The program requests transfer of data using read operation.
• Standard Output(stdout): standard output is the stream where a program writes its output data.
The program requests data transfer using the write operation.
• Standard Error(stderr): it is basically an output stream used by programs to report error
messages or diagnostics. It is stream independent of standard output and can be redirected
separately.
• A stream is linked to a file using an open operation and dissociated from a file using a close
operation.
Buffer associated with file streams
• When a stream linked to a file is created, a buffer is automatically created and associated with
the stream.
• A buffer is nothing but a block of memory that is used for temporary storage of data that has to
be read from or written to a file.
• Buffers are needed because disk drives are block-oriented devices as they can operate efficiently
when data has to be read/written in blocks of certain size.
• The buffer acts as an interface between the stream and the disk hardware. When the program
has to write data to the stream, it is saved in the buffer till it is full. Then the entire contents of
the buffer are written to the disk as a block.
• A text file is a stream of characters that can be sequentially processed by a computer in forward direction.
• Because text files only process characters they read and write one character at a time.
• A line in a text file is not a string in C . Hence it is not terminated by a NULL character.
BINARY FILES:
• A binary file may contain any type of data , encoded in binary form for computer storage and processing
purposes.
• A binary file doesn’t require any special processing of data and each byte of data is transferred to or from the
disk unprocessed.
• Text files can be processed sequentially while binary files can be either processed sequentially or randomly
depending on the need of the application.
Using files in C:
To use files in C, we must follow the steps given below;
• Open a file
• In order to access a particular file from the disk we use a file pointer variable that points to a structure
FILE(defined in stdio.h)
• The file pointer will then be used in all file operations in the program.
• SYNTAX:
FILE *file_pointer_name;
• For example:
• In order to open a file in a computer we use fopen() function: the prototype of fopen() is given below:
• File name could be any name , “file.txt”, “hello.c” or a path name like “/home/user/file1.txt” or a file in D
directory “D:\BMS\Notes\file2.txt”
• Mode: “r”open text file for reading. If The file doesn’t exist throws an error.
• “w”: open a text file for writing. If a file doesn't exist, it creates it and over-writes the contents.
• To close a open file , the fclose() function is used which disconnects a file pointer
from a file.
• Syntax
• int fscanf(FILE *stream,const char *format,..);
• fscanf() is used to read data from the stream and store them
accordingly.
• Format specifiers of scanf and fscanf is similar
#include<stdio.h> fscanf(stdin,"%s %d",name,&roll_no);
exit(0);
Syntax:
The parameter format in fprint() is a C string that contains the text that has
to be written
• The prototype of the format tag can be given as
• %[flags][width][.precision][length]specifier
• Each format specifier must begin with a % sign. The % sign is
followed by
• Flags:
• Width:
• Precision:
• Length:
• Specifier:
Example
if(fp==NULL)
#include<stdio.h>
{
int main()
•fgets( ): The function fgets( ) stands for file get string. This function is used to get a string from a
stream.
•Syntax:
•This function reads at most one less than the number of characters specified by size from the given stream
and stores them in the string str.
•It is terminated when it encounters either a newline character,EOF or any other error.
•When all the characters are read without any error,a ‘\0’ character is appended to the end of the string.
• gets( ) and fgets( ) are almost the same but gets( ) has infinite size and a stream of stdin.
{ fclose(fp);
FILE *fp; return 0;
char str[15]; }
int roll_no;
If input.txt contain bmscecollege
fp=fopen("input.txt","r");
Output is bmscecoll is displayed on monitor
if(fp==NULL)
exit(0);
}
IV. USAGE OF fputs( )
•It writes the string pointed to by str to the stream pointed to by stream.
puts(str);
{
//data stored in a string-str is written to the file input1.txt
FILE *fp;
fp1=fopen("bms.txt","w");
FILE *fp1;
fputs(str,fp1);
char str[26];
fclose(fp1);
int roll_no;
fclose(fp);
fp=fopen(“input.txt","r");
return 0;
if(fp==NULL) }
exit(0);
}
V. USAGE OF fgetc( );(both fgetc( ) and fputc( ))
• fgetc() is used to read the contents from the file character by character.
• fgetc(file_pointer);
int main() //write the data to file input.txt
{ for(i=0;i<length;i++)
FILE *fp; {
fp=fopen("input.txt","w"); fp=fopen("input.txt","r");
if(fp==NULL)
exit(0);
}
while(!feof(fp))
ch=fgetc(fp);
printf("%c",ch);
fclose(fp);
return 0;
}
VI. USAGE OF fputc( ):
• Syntax:
•It will write the byte specified by C( converted to an unsigned char) to the output
stream pointed to by stream.
for(i=0;i<length;i++)
fputc(data[i],fp);
fclose(fp);
return 0; }
VII. USAGE OF fread( )
• Syntax:
•The fread() function reads num number of objects and places them into the array
pointed to by str.
fputc(c,fp);
Pointers
❑ A pointer is a variable which stores the address
of another variable.
❑ A pointer is a derive data type in ‘C’.
❑ Pointers can be used to access and manipulate
data stored in memory.
Example:
int *ptr;
int Var;
Var=10;
ptr=&Var;
a=38;
p=&a;
a=38;
p=&a;
a=38;
p=&a;
Output:
}
&a=fb6f9c a=38
The %p is used to print the pointer value,
p=fb6f9c *p=38
and %x is used to print hexadecimal
values. Though pointers can also be
displayed using %u, or %x.
22 August 2023 CSE, BMSCE 7
Question
Find the output of following program
#include <stdio.h>
main() {
int a, *p;
float b, *q;
a=38;
p=&a;
printf("&a=%x a=%d\n",&a,a);
printf("p=%x *p=%d\n",p,*p);
b=47.5;
q=&b;
printf("&b=%x b=%f\n",&b,b);
printf("q=%x *q=%f\n",q,*q);
}
a=38;
p=&a;
printf("&a=%x a=%d\n",&a,a);
printf("p=%x *p=%d\n",p,*p);
b=47.5;
q=&b; Output:
printf("&b=%x b=%f\n",&b,b); &a=a0e98050 a=38
printf("q=%x *q=%f\n",q,*q); p=a0e98050 *p=38
} &b=a0e98054 b=47.50
q=a0e98054 *q=47.50
Write a program to find area and printf ( "Enter radius of a circle " ) ;
perimeter of a circle using pointers scanf ( "%d", &radius ) ;
#include <stdio.h>
int main()
{
int num1, num2, sum;
int *ptr1, *ptr2;
return 0;
}
Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;
p=&u;
q=&v;
Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;
p=&u;
q=&v;
Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;
p=&u;
q=&v;
Output:
printf("%d %d\n", *p+*q, u+v);
25 25
}
Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;
p=&u;
q=&v;
Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;
p=&u;
q=&v;
Output:
printf("%d %d\n", *p+*q, u+v);
25 25
printf(“%d\n”,*p*u);
400
}