0% found this document useful (0 votes)
17 views13 pages

PPS V Unit

Uploaded by

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

PPS V Unit

Uploaded by

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

FILES :

Files are used to store the information permanently and to access


information whenever necessary. Files are stored in the Secondary
Storage Devices like Floppy Disks, Hard Disks etc. Unlike other
programming languages, C does not distinguish between sequential and
direct access (random access) files.
There are two different types of files in C. They are
 Stream – Oriented (or Standard) files
 System-Oriented (or Low-Level) files.

STREAMS:

All input and output operations in C is performed with streams.


Stream is a sequence of characters organized into lines (text stream),
each line consists of 0 or more characters and ends with the newline
character ‘\n’. Streams provide communications channels between files
and programs. A stream can be connected to a file by opening it and the
connection is broken by closing the stream.
When program execution begins, three files and their associated
streams are connected to the program automatically. They are
 the standard input stream
 the standard output stream
 the standard error stream

Standard input: It is connected to the keyboard & it enables a program


to read data from the keyboard.

Standard output: It is connected to the screen & it enables a program to


write data to the screen.

Standard error: It is connected to the screen & all error messages are
output to standard error.

Operating systems often allow these streams to be redirected to other devices;


Standard input, standard output and standard error are manipulated with file
pointers stdin, stdout and stderr.
BINARY FILES:

Binary files contain fixed length records, They are in binary format
(machine readable) not a human readable format like text files, Binary
files can be accessed directly (i.e. random access). The record structure
for a binary file is created using structures. They are more efficient than
text files as conversion from ASCII to binary (reading) and vice versa for
writing does not have to occur. They cannot be read easily by other non-C
programs. Binary files are appropriate for online transaction processing
systems.
Ex: Airline reservation, Order processing, banking systems.

fwrite function:

The function fwrite is used to write to a binary file.

SYNTAX:
size_t fwrite (void *ptr, size_t size, size_t n, FILE *fptr);

 fwrite writes from array ptr, n objects of size, size to file pointed to
by fptr
 fwrite returns the number of objects written
 which is less than n if an error occurs

fread: The function fread is used to read from a binary file.

SYNTAX:

size_t fread (void *ptr, size_t size, size_t n, FILE *fptr);

 fread reads n objects of size size from a file pointed


to by fptr, and places them in array ptr
 fread returns the number of objects read which may be less than
the number requested
 call to feof() is necessary to distinguish EOF and error condition.
TEXT FILES:
Texts files are classified in to two types.
These are: 1.Formatted Text files
2. Unformatted text files
FORMATTED TEXT FILE :

Formatted Text files contain variable length records must be


accessed sequentially, processing all records from the start of file to
access a particular record.

For formatted input and output to files we use fprintf and fscanf
functions. These functions are the same as printf and scanf except that
the output is directed to the stream accessed by the file pointer, fptr.
fprintf :
fprintf is used to write a record to the file.

Syntax: int fprintf (FILE *fptr, const char* fmt,...)

Ex :fprintf (fptr,"%d %s %.2f\n",accNo,name,balance);

fprintf returns the number of characters written or negative if an error


occurs.

fscanf :
fscanf is used toRead a record from the file.

Syntax: int fscanf (FILE *fptr, const char* fmt, ... )


Ex :fscanf (fptr,"%d %20s %f",&accNo,name, &balance);

fscanf returns the number of input items assigned or EOF if an error or


EOF occurs before any characters are input.Rewind(FILE* ptr) - resets the
current file position to the start of the file.

SEARCHING THE FILE:

Accessing a particular record(s) requires


– a sequential read from the start of the file
– testing each record to see is it being searched for
– reset the file pointer to the start of the file ready for the next
search.

UPDATING RECORDS:
Records cannot be updated, to update a text file the entire file is
rewritten.

UNFORMATTED TEXT FILES:


stdio.h provides many functions for reading and writing to
unformatted text files.

fgetc( ): This function is used to read the next character from the stream.
This is similar to getchar().
Synta : int fgetc (FILE *stream)
It returns the character (as an integer) or EOF if end of file or an error
occurs.

fputc( ): This function is used to write the character c to the stream. This
is similar to putchar (int).
Syntax: int fputc (int c, FILE *stream)
It returns the character or EOF for error.

fgets( ): This function Reads at most the next n-1 characters from the
stream into the array s. Reading stops after an EOF or a newline. If a
newline is read, it is stored into the buffer. A '\0' is stored after the last
character in the buffer. This is similar to gets(char* ).
Syntax : char* fgets (char *s,int n,FILE *stream)
It returns s or NULL if EOF or error occurs

fputs( ): This is used to write the string s to the stream. This is


similar to puts(const char*).
Syntax : int fputs (const char *s, FILE *stream)
It returns EOF for error.

Positioning the File Pointer:


fseek( ): fseek is used to position the file pointer at the appropriate
record in the file before reading or writing a record. The function fseek
sets the file position for a stream. Subsequent reads and writes will access
data in the file beginning at the new position
SYNTAX: int fseek (FILE *fp, long offset, int origin)
• The position is set to the offset from the origin
• fseek returns non zero on error

fseek takes 3 arguments


• fp the file pointer for the file in question
• offset is an offset in a file we want to seek to
• origin is the position that the file pointer is set to origin can be
either SEEK_SET - beginning of file, SEEK_CUR - current position in
file, SEEK_END - end of file.

It may be necessary when performing a number of different types of


access to a single file to reset the file pointer in certain instances.
Ex: searching for a particular record in a file may leave the file pointer in
the middle of the file.
To write a new record to this file the pointer should be reset to point to
the end of file.

ftell() function returns the current file position of the specified stream.

ftell() function is used to get the total size of a file after moving file pointer
at the end of file. We can use SEEK_END constant to move the file pointer
at the end of file.

Syntax: long int ftell(FILE *stream)

rewind( ) :The function rewind resets the file pointer back to the start of
file.

Syntax : void rewind (FILE *fp)


rewind(fp) is equivalent to fseek(fp,0,SEEK_SET).

feof( ) : The function feof tests for end of file.


Syntax : int feof(FILE *fptr)
Feof accepts a pointer to a FILE, It returns non-zero if EOF and zero
otherwise. It is used when reading a file to check whether the EOF has
been reached

STEPS IN WORKING WITH FILES:

• Establish a Buffer Area


• Opening a File
• Reading from a File or Writing to a File
• Closing a File.
I. Establish a Buffer Area :
The first step is to establish a buffer area, where the information is
temporarily stored while being transferred between the computer’s
memory and the file.
The Buffer Area is established by writing
FILE *ptrvar;

FILE is a Structure which has been defined in the header file


“stdio.h” (Standard input/output header file), which is a link between the
Operating System and Program. It is necessary to include the header file
“stdio.h”. The FILE Structure contains information about the file being
used, such as its current size, its location in memory etc. This buffer area
allows information to be read from or written to file faster.
*prtvar is a pointer variable, which contains address of the Structure FILE.

2. Opening a File:
A File must be opened before it can be created or processed. This
association the file name with the buffer area. It also specifies how the file
will be utilized i.e. read-only file, write-only file, or read/write file.
We use the library function fopen() for opening a file. ptrvar =
fopen(filename, mode)
where filename and mode are strings. Filename represent the name
of the file, mode represents how the file opened i.e., read only, write only
etc.
The fopen() function returns a pointer to the begins of the buffer
area associated with the file. A NULL value is returned if the file cannot be
created or when existing file cannot be found.
The different file opening modes area listed below.

Mode Meaning
“r” Open an existing file for reading only
“w” Open a new file for writing only. If the file exists, its
contents are over written.
“a” Open an existing file for appending (i.e., for adding
new information at the end of the file). A new file will
be created if the file does not exist.
“r+” Open an existing file for both reading and writing.
“w+” Open a new file for both reading and writing. If the
file exists, the contents are over written
“a+” Open an existing file for both reading and appending.
A new file will be created if the file does not exists
To open the file in Binary file mention the mode along with a extra letter
‘b’ as “rb”,
“wb”, “rb+” and so on.

3. Reading /Writing form/to a File:

After opening the file we can read the characters from a file or write the
characters into the file by using the two library functions fgetc() and
fputc().
fgetc()  reach a character from the current position and advances the
pointer position to the next character, and returns the character that is
read.
Eg:- ch = fgetc(ptrvar)

fputc()  Writes a character into the file.


Eg:- fputc(ch,ptrvar)

fscanf( ) and fprintf( ) are two functions used for formatted reading and
writing of characters, Strings, integers and floats.
fprintf(FILE *fp,"format-string",var-list);
fscanf(FILE *fp,"format-string",var-list);

fread( ) and fwrite( ):


These are two functions to read and write structures with file in
binary mode.
The Syntax is as follows:

fwrite(&record, sizeof(record), no of records, fileptr);


fread(&record, sizeof(record), no of records, fileptr);
The first argument is the address and the structure.
The second argument is the size of the structure in bytes.
The third argument is the number of structures to read or write. The last
argument is pointer to the file.

4. Closing the File :

Finally, the file must be closed at the end of the program. This can
be done by using the function fclose().

Syntax: fclose(ptrvar);
It is good programming practice to close a file explicitly, even
though C compiler will automatically close the file.

/* Program to Create a File */


main()
{
FILE *fp;
char ch;
fp = fopen(“chars”,’w’);
printf(“Enter the characters(enter * to stop)\n”);
while((ch=getchar())!=’*’)
putc(ch,fp);
printf(“File Created”);
fclose(fp);
}

/* Program to Create a read an Existing File */


#include<stdio.h> main()
{
FILE *fp;
char ch;
fp = fopen(“chars”,’r’);
printf(“The contents of the file are:\n”);
while((ch=fgetc(fp))!=EOF)
printf(“%c”,ch);
fclose(fp);
}

/* Program to Copy One File to Another File */

#include<stdio.h>
main()
{
FILE fs,ft; char ch;
fs = fopen(“source”,’r’);
if(fs = =NULL)
{
puts(“Cannot open source file”);
exist();
}
fr = fopen(“target”,’w’);
if(ft = =NULL)
{
puts(“Cannot open target file”);
fclose(fs);
exist();
}
while((ch=fgetc(fs))!=EOF)
putc(ch,ft);
printf(“File Copied”);

fclose(fs);
fclose(ft);
}
/* Program to illustrate the use of fprintf() */
#include<stdio.h>
main()
{
FILE *fp;
char itemname[20]; int qty;
float rate;
char choice = ‘y’;
fp = fopen (“Item”,”w”);
while (choice = = ‘y’)
{
printf(“Enter Item Name, Quantity and Rate \n”); scanf(“%s%d
%f”,itemname,&qty,&rate);
fprintf(fp, “%s%d%f\n”,itemname, age,rate);
printf(“Do you want to Continue (y/n)”);
fflush(stdin);
choice = getch();
}
fclose(fp);
}
/* Program to illustrate the use of fscanf() */

#include<stdio.h>
main()
{
FILE *fp;
char itemname[20];
int qty;
float rate;
fp = fopen (“Item”,”r”);
while (fscanf(fp,“%s%d%f”,itemname,&qty,&rate)!=EOF)
{
printf(“Item Name : %s\n”,itemname);
printf(“Quantity =%d\n”,qty);
printf(“Rate = %f\n”,rate);
}
fclose(fp);
}

/* Program for writing records into a file using Structures */


#include<stdio.h>
main()
{
FILE *fp;
char choice = ‘y’;
struct emp
{
char name[40];
int age;
float bs;
};
struct emp e;
fp = fopen(“emp.dat”, “w”);
if(fp = = NULL)
{
puts(“Cannot open file”);
exit();
}
while (choice = =’y’)
{
printf(“Enter Name, age and Basic Salary”);
scanf(“%s%d%f”, e.name, &e.age, &e.bs);
fprintf(fp, “%s%d%f\n”,e.name,e.age,e.bs);
printf(“Do you want to add one more record (y/n)”);
fflush(stdin);
choice =getch();
}
fclose(fp);
}
/* Writing records into file in Binary Mode */

#include<stdio.h>
main()
{
FILE *fp;
char choice = ‘y’;
struct emp
{
char name[20];
int age;
float bs;
};
struct emp e;
fp = fopen(“Employee.dat”, “wb”);
if(fp = = NULL)
{
puts(“Cannot open file”);
exit();
}
while (choice = =’y’)
{
printf(“Enter Name, age and Basic Salary”);
scanf(“%s%d%f”, e.name, &e.age, &e.bs);
fwrite(&e,sizeof(e),1,fp);
printf(“Do you want to add one more record (y/n)”);
fflush(stdin);
choice =getch();
}
fclose(fp);
}

/* Read the records from Binary File */

#include<stdio.h>
main()
{
FILE *fp;
struct emp
{
char name[20];
int age;
float bs;
};
struct emp e;
fp = fopen(“Employee.dat”, “rb”);
if(fp = = NULL)
{
puts(“Cannot open file”);
exit();
}
while (fread(&e,sizeof(e),1,fp)
{
printf(“\n Employee Name : %s\n”,e.name);
printf(“\n Employee Age:%d”,e.age);
printf(“\nBasic Salary = %f”,e.bs);
}
fclose(fp);
}

/* Program for copying one file to another file using command line
arguments */

#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fs, *ft;
Char ch;
if (argc!=3)
{
puts(“In sufficient arguments”);
exit();
}
fs = fopen(argv[1], “r”);
if (fs= =NULL)
{
puts(“Cannot open source file”);
exit();
}
ft = fopen(argv[2],”w”);
if (ft = =NULL)
{
puts(“Cannot open target file”);
fclose(fs);
exit();
}
while ((ch=fgetc(fs))!=EOF)
fputc(ch,ft);
fclose(fs);
fclose(ft);
}

You might also like