Module 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Unit 5 : Files

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.

Program Buffer Disk


Program
writes data Data from the
to buffer buffer is
written to the
disk file
Contd…
• Similarly, when reading the data from a disk file, the data is read as a block from the file and
written into the buffer. The program reads data from the buffer. The creation and operation of
the buffer is automatically handled by the operating system.
• C provides some functions for buffer manipulation.
• The data resides in the buffer until the buffer is flushed or written to a file.
Types of files
ASCII TEXT FILES:

• 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.

• A file is terminated by a special character called the end-of-file(EOF)

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;

• Declare a file pointer variable

• Open a file

• Process the file

• Close the file


DECLARING A FILE POINTER VARIABLE:

• 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:

FILE *fp; // fp is declared as a file pointer


OPENING A FILE:
• A file should be opened before a data could be read from it or written to it.

• In order to open a file in a computer we use fopen() function: the prototype of fopen() is given below:

• FILE *fopen(const char *file_name, const char *mode);

• 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” “w” “a” “r+” “w+” “a+”, rb, wb

• fopen() returns pointer-to-structure on successful creation of file, returns NULL otherwise.

• 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.

• “a”: append data to a file.If File doesn’t exists it is created.

• Similarly, “rb”,”wb”,”ab” for binary files.


File Name
• Every file on the disk has a name associated with it.
• Windows have restrictions on usage of certain characters in the
filenames, i.e., characters such as /,\,:,*,?,”,<,> and ! Cannot be a part
of a filename.
Example: D:\\BCA\\Student.DAT
FILE MODE
CLOSING A FILE:

• To close a open file , the fclose() function is used which disconnects a file pointer
from a file.

• Prototype of the function fclose() is;

int fclose(FILE *fp);

• Returns 0 if function was successful

• Non-zero value is returned if an error occurred.


1)Write a C program to display if a file is successfully created or not. (use : online gdb)
3. READING DATA FROM FILES :

• C provides set of functions to read data from a file ,They are:


fscanf( ) , fgets( ) , fgetc( ) , fread( )
4. WRITING DATA TO FILES :

•C provides set of functions to write data to a file ,They are:

• fprintf( ) , fputs( ) , fputc( ) , fwrite( )


I. Usage of fscanf( ) in files
•fscanf(): is similar to the scanf( ) function, except that the first argument of
fscanf( ) specifies a stream from which to read(stdin or fp), whereas scanf() can
only read from standard input(stdin).

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

int main() printf("name=%s, roll_no=%d\n \n",name,roll_no);

{ //reading name and rollno from another


file(input.txt)
FILE *fp;
fscanf(fp,"%s %d",name,&roll_no);
char name[20]; int roll_no;
printf("name=%s, roll_no=%d",name,roll_no);
fp=fopen("input.txt","r");
fclose(fp);
if(fp==NULL)
return 0;
{
}
printf("the file couldn't be opened\n");

exit(0);

} //reading name and rollno from keyboard

printf("enter the name and rollno\n");


II. USAGE OF fprintf( )

This is used to write the formatted output to a stream.

Syntax:

int fprintf(FILE * stream, const char * format ,…) ;

The function writes data that is formatted as specified by the format


argument.

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

{ printf("the file couldn't be opened\n");

FILE *fp; exit(0);


char name[20]; }
int age; fprintf(fp,"%s %d",name,age);
printf("enter your name and age\n");
fclose(fp);
scanf("%s\t%d",name,&age);
return 0;
fp=fopen("input.txt","w");
}
III.Usage of fgets( )

•fgets( ): The function fgets( ) stands for file get string. This function is used to get a string from a
stream.

•Syntax:

•char *fgets(char *str,int size,FILE *stream);

•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.

•On successful completion,fgets() will return str.


#include<stdio.h>
fgets(str,10,fp);

int main() puts(str);

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

printf("the file couldn't be opened\n");

exit(0);

}
IV. USAGE OF fputs( )

•Opposite of fgets is fputs( ).

•The fputs() is used to write a line to a file.

•int fputs(const char *str, FILE *stream);

•It writes the string pointed to by str to the stream pointed to by stream.

•On successful completion, fputs( ) returns 0 ,on error it returns EOF.


#include<stdio.h> //data read from the file input.txt and stored in array- str

int main() fgets(str,10,fp);

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

{ If input.txt contain bmscecollege

printf("the file couldn't be opened\n"); Output is bmscecoll is stored in bms.txt

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

char ch; fputc(data[i],fp);

char data[25]="BMS COLLEGE"; }

int length =strlen(data); fclose(fp);

int i; //read the data using fgetc()

fp=fopen("input.txt","w"); fp=fopen("input.txt","r");

if(fp==NULL)

printf("the file couldn't be opened\n");

exit(0);

}
while(!feof(fp))

ch=fgetc(fp);

printf("%c",ch);

fclose(fp);

return 0;

}
VI. USAGE OF fputc( ):

•this is opposite of fgetc().

• This function write a character to the stream.

• Syntax:

•int fputc(int c, FILE *stream);

•It will write the byte specified by C( converted to an unsigned char) to the output
stream pointed to by stream.

•On successful completion,fputc() will return the value it has written.

•In case of error,the function will return EOF.


int i;
#include<stdio.h> fp=fopen("input.txt","w");
int main() if(fp==NULL)
{ {
FILE *fp; printf("the file couldn't be opened\n");
char data[25]="BMS COLLEGE"; exit(0);
int length =strlen(data); }

for(i=0;i<length;i++)

fputc(data[i],fp);

fclose(fp);

return 0; }
VII. USAGE OF fread( )

• The fread() function is used to read data from a file

• Syntax:

•int fread(void *str,size_t size, size_t num,FILE *stream);

•The fread() function reads num number of objects and places them into the array
pointed to by str.

•The data is read from the given input stream.

•Upon successful completion,fread() returns the number of bytes successfully read.


Example program:
• Demonstrate how to read data from the keyboard, write it to a file called INPUT, again read the same
data from the INPUT file, and display it on the screen/console.
#include <stdio.h> fclose(fp); /* Close the file INPUT */

int main() printf("\nData Output\n\n");

{ /* Reopen the file INPUT */

FILE *fp; fp = fopen("INPUT.dat","r");

char c; /* Read a character from INPUT*/

printf("Data read from the keyboard : Input\n\n"); while((c=fgetc(fp)) != EOF)

/* Open the file INPUT */ /* Display a character on screen */

fp = fopen("INPUT.dat", "a"); printf("%c",c);

/* Get a character from keyboard */ /* Close the file INPUT */

while((c=getchar()) != EOF) fclose(fp);

/* Write a character to INPUT */ }

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.

22 August 2023 CSE, BMSCE 1


Advantages of Pointers
❑ Pointers are more efficient in handling arrays and data
tables.
❑ Pointers can be used to return multiple values from a
function.
❑ Pointers allow ‘C’ to support dynamic memory
management.
❑ Pointers provide an efficient tool for manipulating
dynamic data structures such as stack, queue etc.

22 August 2023 CSE, BMSCE 2


Declaring Pointer variable
DataType *Pointer_var_name;

22 August 2023 CSE, BMSCE 3


Declaring Pointer variable
DataType *Pointer_var_name;

Example:
int *ptr;
int Var;

Var=10;
ptr=&Var;

22 August 2023 CSE, BMSCE 4


Example Program
#include <stdio.h>
main() {
int a, *p;

a=38;
p=&a;

22 August 2023 CSE, BMSCE 5


Example Program
#include <stdio.h>
main() {
int a, *p;

a=38;
p=&a;

printf("&a=%x a=%d\n", &a,a);


printf("p=%x *p=%d\n",p,*p);

22 August 2023 CSE, BMSCE 6


Example Program
#include <stdio.h>
main() {
int a, *p;

a=38;
p=&a;

printf("&a=%x a=%d\n", &a,a);


printf("p=%x *p=%d\n",p,*p);

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

22 August 2023 CSE, BMSCE 8


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

22 August 2023 CSE, BMSCE 9


Pointer Expressions and Pointer Arithmetic

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> areaperi ( radius, &area, &perimeter ) ;


void areaperi ( int r, float *a, float *p )
{ printf ( "Area = %f", area ) ;
*a = 3.14 * r * r ; printf ( "Perimeter = %f", perimeter ) ;
*p = 2 * 3.14 * r ; }
}
Output
void main( )
{
int radius ;
float area, perimeter ;

22 August 2023 CSE, BMSCE 10


Write a c program to test whether a number is
positive, negative ,or equal to zero

22 August 2023 CSE, BMSCE 11


Program to add two numbers using pointers

#include <stdio.h>

int main()
{
int num1, num2, sum;
int *ptr1, *ptr2;

ptr1 = &num1; // ptr1 stores the address of


num1
ptr2 = &num2; // ptr2 stores the address of
num2

printf("Enter any two numbers: ");


scanf("%d%d", ptr1, ptr2);

sum = *ptr1 + *ptr2;

printf("Sum = %d", sum);

return 0;
}

22 August 2023 CSE, BMSCE 12


Arithmetic Operations on Pointer variables

Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;

p=&u;
q=&v;

22 August 2023 CSE, BMSCE 13


Arithmetic Operations on Pointer variables

Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;

p=&u;
q=&v;

printf("%d %d\n", *p+*q, u+v);


}

22 August 2023 CSE, BMSCE 14


Arithmetic Operations on Pointer variables

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
}

22 August 2023 CSE, BMSCE 15


Arithmetic Operations on Pointer variables

Example Program
#include <stdio.h>
main() {
int u=20, v=5;
int *p, *q;

p=&u;
q=&v;

printf("%d %d\n", *p+*q, u+v);


printf(“%d\n”,*p*u);
}

22 August 2023 CSE, BMSCE 16


Arithmetic Operations on Pointer variables

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
}

22 August 2023 CSE, BMSCE 17

You might also like