• No results found

Structured Programming Unit-15 File Input / Output [4 hrs]

N/A
N/A
Protected

Academic year: 2021

Share "Structured Programming Unit-15 File Input / Output [4 hrs]"

Copied!
28
0
0

Loading.... (view fulltext now)

Full text

(1)

Structured Programming

Unit-15

File Input / Output

[4 hrs]

(2)

Introduction

• Data file allows us to store information permanently on the

auxiliary memory device in certain format, and to access and

alter that information whenever necessary.

• In C, extensive set of library functions is available for

creating and processing data files.

• There are two different types of data files that C

programming handle.

1. High level I/O functions (also called standard I/O or

stream I/O functions)

2. Low level file I/O functions (also called system I/O

functions)

(3)

Stream

• A stream is a series of ordered bytes.

• A stream is a source or destination of data that may be

associated with a disk or other peripheral.

• The c library stdio.h supports text streams and binary streams.

A text stream is a sequence of lines; each line has zero or more

characters and is terminated by '\n'.

• A binary stream is a sequence of unprocessed bytes that record

internal data, with the property that if it is written, then read

back on the same system, it will compare equal.

• A stream is connected to a file or device by opening it; the

connection is broken by closing the stream.

• Opening a file returns a pointer to an object of type FILE, which

records whatever information is necessary to control the

stream. We will use “file pointer” and “stream”

interchangeably when there is no ambiguity.

http://genuinenotes.com

(4)

Working with file

• C supports a number of functions that have the ability to

perform basic file operations, which include:

• 1-Naming a file

• 2-Opening a file

• 3-Reading from a file

• 4-Writing data into a file

• 5-Closing a file

• When working with a stream-oriented data file, the first step

is to establish the buffer area, where information is

temporarily stored while being transferred between the

computer’s memory and the data file.

• The buffer area is established by writing

(5)

Opening File

• The library function fopen is used to open a file. This

function is typically written as

ptvar= fopen(file-name, file-type);

• Where file-name and file-type are strings that

represent the name of the data file and the manner

in which the data file will be utilized and ptvar is

pointer to the FILE structure.

• The FILE structure contains information about the

file being used, such as its current size, its location in

memory etc.

(6)

Closing File

• When we have finished reading from the file,

we need to close it.

• This is done using the function fclose()

through the statement,

(7)

File Opening Modes(file type)

File Mode

Tasks Performed

r Searches file. If the file exists loads if into memory and sets up

a pointer, which points to the first character in it. If the file doesn’t exist it returns NULL. Operations possible – reading from the file.

w Search file. If the file exists, its contents are overwritten. If the

file doesn’t exit, a new file is created. Returns NULL, if unable to open file. Operation possible – writing to the file.

a Searches file. If the file exists, loads it into memory and sets

up a pointer which points to the first character in it the file doesn’t exist, a new file is crated. Returns NULL, if unable to open file. Operations possible – appending new contents at the end of file.

(8)

File Opening Modes(file type)

File Mode

Tasks Performed

r+ Searches file. If it exists loads it into memory and sets up a

pointer, which points to the first character in it. If file doesn’t exist it returns NULL.

Operations possible – reading existing contents, writing new contents, modifying existing contents of the file

w+ Search file. Of the file exists, its contents are destroyed. If the file

doesn’t exit a new file is created. Returns NULL, if unable to open file. Operations possible – writing new contents, reading them back and modifying file contents.

a+ Searches file. If the file exits, loads t into memory and sets up a

pointer, which points to the first character in it. If the file doesn’t exits, a new file is crated. Returns NULL, if unable to open file. Operations possible – reading existing contents, appending new contents to end of file. Cannot modify existing contents.

(9)

Working with unformatted text

file

• Unformatted file I/O functions are

• fgetc();-character input function

• fputc();-character output function

• fgets();-line input function

• fputs() ;-line output function

(10)

Character I/O functions Example

#include<stdio.h> #include<process.h> void main() { FILE *fs,*ft; char ch; fs=fopen("File1.txt","r"); if(fs==NULL) {

puts("Cannot open source file"); exit(1);

(11)

Character I/O functions Example

ft=fopen("File2.txt","w"); if(ft==NULL) {

puts("Cannot open target file"); fclose(ft); exit(1); } while(1) { ch=fgetc(fs); if(ch==EOF) break; else fputc(ch,ft); } fclose(fs); fclose(ft); } http://genuinenotes.com

(12)

Program that writes strings to a file

#include<stdio.h>

#include<process.h>

#include<string.h>

void main()

{

FILE *fp;

char s[80];

fp=fopen("F1.txt","w");

if(fp==NULL)

{

puts("Cannot open target file");

fclose(fp);

exit(1);

}

(13)

Program that writes strings to a file

printf("\nEnter a few lines of text:\n"); while(strlen(gets(s))>0) { fputs(s,fp); fputs("\n",fp); } fclose(fp); }

Note that each string is terminated by hitting enter. To terminate the execution of the program, hit enter at the beginning of a line. We have set up a character array to receive the string; the fputs() function then writes the contents of array to the disk. Since fputs() does not automatically add a new line character to the end of the string, we must do this explicitly to read the string back from the file.

(14)

Program that reads strings from a file

#include<stdio.h>

#include<process.h>

void main()

{

FILE *fp;

char s[80];

fp=fopen("F1.txt","r");

if(fp==NULL)

{

puts("Cannot open target file");

fclose(fp);

exit(1);

}

(15)

Program that reads strings from a file

while(fgets(s,79,fp)!=NULL)

{

printf("%s\n",s);

}

fclose(fp);

}

The function fgets() takes three arguments. The first is the

address where the string is stored, and the second is the

maximum length of the string. The third argument is the

pointer to the structure File. When all the lines from the file

have been read, we attempt to read one more line, in which

case fgets() returns a NULL.

(16)

Formatted Disk I/O Functions

• For formatted reading and writing of

characters, strings, integers, float, there

exist two functions, fscanf() and fprintf().

(17)

Writing in a file using Formatted

Disk Output Function

#include<stdio.h> #include<process.h> void main()

{

FILE *fp;

char another ='Y'; char name[40]; int age; float bs; fp=fopen("EMPLOYEE.DAT","w"); if(fp==NULL) {

puts("Cannot open file"); exit(0);

(18)

Writing in a file using Formatted Disk

Output Function

while(another=='Y' || another=='y') {

printf("\nEnter name, age and basic salary\n"); scanf("%s%d%f",name,&age,&bs);

fprintf(fp,"%s %d %f",name,age,bs); printf("\nAnother employee (Y/N)"); fflush(stdin);

another=getchar(); }

fclose(fp); }

In this program the function fprints(), writes the values of three

variables to the file. This function is similar to printf(), except that a FILE pointer is included as the first argument.

The function fflush() is designed to remove any data remaining in the buffer. Here we use ‘stdin’, which means buffer related with

(19)

Reading back from a file using fscanf()

#include <stdio.h> #include<process.h> void main() { FILE *fp; char name[40]; int age; float bs; fp=fopen("EMPLOYEE.DAT","r"); if(fp==NULL) {

puts("Cannot open file"); exit(0);

}

while(fscanf(fp,"%s %d %f",name, &age, &bs)!=EOF) printf("\n%s %d %.2f",name,age,bs);

fclose(fp);

(20)

Binary file Operations

• fread() and fwrite() functions are used for

reading/writing records with binary file. The

following program writes records to a binary

file.

(21)

Writing Records With Binary File

#include<stdio.h> #include<process.h> void main() { FILE *fp; char another='Y'; struct emp { char name[40]; int age; float bs; }; struct emp e; fp=fopen("EMP.DAT","wb"); http://genuinenotes.com

(22)

Reading Records With Binary File

if(fp==NULL)

{

puts("Cannot open file"); exit(0);

}

while(another=='Y' || another=='y') {

printf("\nEnter name,age and basic sal.\n"); scanf("%s %d %f", e.name,&e.age,&e.bs); fwrite(&e,sizeof(e),1,fp);

printf("\n add another record(Y/N)"); fflush(stdin);

another=getchar(); }

(23)

Writing Records to Binary File

#include<stdio.h>

#include<process.h>

void main()

{

FILE *fp;

struct emp

{

char name[40];

int age;

float bs;

};

struct emp e;

fp=fopen("EMP.DAT","rb");

http://genuinenotes.com

(24)

Writing Records to Binary File

if(fp==NULL)

{

puts("Cannot open file");

exit(0);

}

while(fread(&e,sizeof(e),1,fp)==1)

printf("\n%s %d %.2f", e.name,e.age,e.bs);

fclose(fp);

}

(25)

Moving File Pointer

• We can use rewind(), fseek() and ftell() for moving file pointer

position.

• The rewind() function can be used in sequential or random access

C file programming, and simply tells the file system to position the

file pointer at the start of the file.

• The fseek() function is most useful in random access files where

either the record (or block) size is known, or there is an allocation

system that denotes the start and end positions of records in an

index portion of the file.

• The fseek() function takes three parameters:

– FILE * f – the file pointer;

– long offset – the position offset;

– int origin – the point from which the offset is applied. http://genuinenotes.com

(26)

Moving File Pointer

• The origin parameter can be one of three values:

– SEEK_SET – from the start;

– SEEK_CUR – from the current position; – SEEK_END – from the end of the file.

• So, the equivalent of rewind() would be:

• fseek( f, 0, SEEK_SET);

• By a similar token, if the programmer wanted to append a record

to the end of the file, the pointer could be repositioned thus:

• fseek( f, 0, SEEK_END);

• There is a function called ftell() that can be called to find out the

current offset within the file:

(27)

Things to Remember

• The file position indicator can be reset by the fseek() function.

• The ftell() function can tell you the value of the current file

position indicator.

• The rewind() function can set the file position indicator to the

beginning of a file.

• After you specify the mode of the fopen() function for the binary

file, you can use the fread() or fwrite() functions to perform I/O

operations on binary data.

• Besides the fact that the fscanf() and fprintf() functions can do

the same jobs as the scanf() and printf() functions, the fscanf()

and fprintf() functions also allow the programmer to specify I/O

streams.

• You can redirect the standard streams, such as stdin and stdout,

to a disk file with the help of the freopen() function.

http://genuinenotes.com

(28)

Self Practice Questions

1. Write a program to read the text file goods.txt and count the number of characters in the file. Also, print out the contents of the file and the total character number on the screen.

2. Write a program that reads a line of text and writes only those words which starts with ‘a’ to the file named “a.txt”. Remember that the content of the file “a.txt” must not be erased with new entry.

3. Write program that stores information (name, roll, age, and address as attributes) of students in a file. In this file new records of students

should be added without affected existing records of students. 4. Write a program to store record of N employees in a file named

‘employee.dat’. Records contain attributes such as name, id, branch and post of employee. Then after reading from the file display the records of those employees whose branch lies at ‘NewRoad’ and post is ‘manager’.

References

Related documents