36
www.eshikshak.co.in

Mesics lecture files in 'c

Embed Size (px)

DESCRIPTION

File Handling in 'C'

Citation preview

Page 1: Mesics lecture   files in 'c

www.eshikshak.co.in

Page 2: Mesics lecture   files in 'c

A collection of data or information that has a are stored on computer known as file

A file is collection of bytes stored on a secondary storage device.

There are different types of file Data files Text files Program files Directory files

Different types of file stored different types of information

Page 3: Mesics lecture   files in 'c

A file has a beginning and an end, it has a current position, typically defined as on many bytes from the beginning.

You can move the current position to any other point in file.

A new current position can be specified as an offset from the beginning the file.

Page 4: Mesics lecture   files in 'c

A stream is an abstract representation of any external source or destination for data, so the keyword, the command line on your display and files on disk are all examples of stream.

‘C’ provides numbers of function for reading and writing to or from the streams on any external devices.

Page 5: Mesics lecture   files in 'c

A stream is a series of bytes data flow from your program to a file or vice-versa.

There are two formats of streams which are as follows Text Stream▪ It consists of sequence of characters, depending on

the compilers▪ Each character line in a text stream may be

terminated by a newline character.▪ Text streams are used for textual data, which has a

consistent appearance from one environment to another or from one machine to another

Page 6: Mesics lecture   files in 'c

A stream is a series of bytes data flow from your program to a file or vice-versa.

There are two formats of streams which are as follows Binary Stream▪ It is a series of bytes.▪ Binary streams are primarily used for non-

textual data, which is required to keep exact contents of the file.

Page 7: Mesics lecture   files in 'c
Page 8: Mesics lecture   files in 'c

A text file can be a stream of characters that a computer can process sequentially.

It is processed only in forward direction.

It is opened for one kind of operation (reading, writing, or appending) at any give time.

It can read only one character at a time.

Page 9: Mesics lecture   files in 'c

A binary file is collection of bytes. In ‘C’ both a both a byte and a

character are equivalent.A binary file is also referred to as a

character stream, but there are two essential differences.

Page 10: Mesics lecture   files in 'c
Page 11: Mesics lecture   files in 'c
Page 12: Mesics lecture   files in 'c

A file is identified by its name.This name is divided into two parts

File Name▪ It consists of alphabets and digits.▪ Special characters are also supported, but it

depends on operating system. Extension▪ It describe the file type

Page 13: Mesics lecture   files in 'c

Before opening a file, we have to create a file pointer.

FILE structure is defined in the “stdio.h” header file.

It stores the complete information about file. Name of file, mode it is opened in, starting buffer

address, a character pointer that points to the character being read.

Page 14: Mesics lecture   files in 'c

To perform any operation (read or write) the file has to be brought into memory from the storage device.

Thus, bringing the copy of file from disk to memory is called opening the file.

Page 15: Mesics lecture   files in 'c

Mode Meaning

r Open a text file for reading only. If the file doesn’t exist, it returns null.

w Opens a file for writing only. If file exists, than all the contents of that file are destroyed and new fresh blank file is copied on the disk and memory with same name If file dosen’t exists, a new blank file is created and opened for writing. Returns NULL if it is unable to open the file

a Appends to the existing text file Adds data at the end of the file. If file doesn’t exists then a new file is created. Returns NULL if it is unable to open the file.

rb Open a binary file for reading

wb Open a binary file for reading

ab Append to a binary file

r+ Open a text file for read/write

w+ Opens the existing text file or Creates a text file for read/write

Page 16: Mesics lecture   files in 'c

Mode Meaning

a+ Append or create a text file for read/write

r+b Open a binary file for read/write

w+b Create a binary file for read/write

a+b Append a binary file for read/write

Page 17: Mesics lecture   files in 'c

fopen() function, like all the file-system functions, uses the head file stdio.h

The name of the file to open is pointed to by fname

The string pointed at for mode determined how the file may be accessed.

Page 18: Mesics lecture   files in 'c

FILE *fp;if(fp = fopen(“myfile”,”r”)) == NULL){printf(“Error opening a file”);

exit(1);}

Page 19: Mesics lecture   files in 'c

When we want to read contents from existing file, then we require to open that file into read mode that means “r” mode

To read file follow the below steps1. Initialize the file variable2. Open a file in read mode3. Accept information from file4. Write it into the output devices5. Repeat steps 3 and 4 till file is not ends6. Stop procedure

Page 20: Mesics lecture   files in 'c

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

FILE *fp; char ch;

fp=fopen(“clear.c”,”r”); if(fp==NULL) print(“Unable to open clear.c”);

else{

do{

ch = getc(fp);putchar(ch);

}while(ch!=EOF); fclose(fp);

}}

Page 21: Mesics lecture   files in 'c

A file contains a large amount of data.

We some times cannot detect the end of file.

In text file, a special character EOP denotes the end-of-file

Page 22: Mesics lecture   files in 'c

To close a file and dis-associate it with a stream, use fclose() function.

It returns 0 if successful else returns EOP if error occurs.

The fcloseall() closes all the files opened previously.

Page 23: Mesics lecture   files in 'c

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

FILE *fp; char ch;

fp=fopen(“clear.c”,”r”); if(fp==NULL) print(“Unable to open clear.c”);

else{

do{

ch = getc(fp);// gets the character from file

putchar(ch);}while(ch!=EOF);

fclose(fp);}

}

Page 24: Mesics lecture   files in 'c

We can add contents to the existing file whenever it is required.

Perform the following steps1. Initialize the variable2. Open a file in append mode3. Accept information from user4. Write it into the file5. Repeat steps 3 and 4 according to

user’s choice6. Stop procedure

Page 25: Mesics lecture   files in 'c

char *fgets(char *str, int n, FILE *fptr); This statement reads character from the

stream fptr into to the character array ‘str’ until a new line character is read or end of file is reached or n-1 characters have been read.

fputs(const char *str, FILE *fptr); This statement writes to the stream fptr

except the terminating null character of string ‘str’

Page 26: Mesics lecture   files in 'c

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

FILE *fp; char line[280];int ch, i=0;

fp=fopen(“a.dat”,”a”); if(fp==NULL) print(“Unable to open clear.c”);

else {do{

do{line[i++] = getchar();

}while(line[i-1]!=‘*’);fputs(line, fp);//Writes string to the filei=0;printf(“\nPress 1 to continue”);scanf(“%d”,&ch);

}while(ch==1); fclose(fp);

printf(“File is successfully created”);}

}

Page 27: Mesics lecture   files in 'c

We can modify the files in two ways Serial access Random access

Generally all the text files are considered to be sequential files because lines of text files or records of the formatted files are not equal.

So address of each record is un predictable Whereas, in random access file all the

record length are same.

Page 28: Mesics lecture   files in 'c

To modify the file open the file with read and write mode

“r+” or “w+” or “a+” Generally “r+” mode is use for this purpose

1. Initialize the variable2. Open a file in read/write mode3. Read information from file4. Print it5. Check whether the information is right or wrong?1. If Wrong, accep correct information from user, move the file

pointer to the start of record or information. Re-write it that means new information into the file.

2. If not wrong, go to step 6.

6. Repeat steps 3 to 6 till file is not end.7. Stop procedure

Page 29: Mesics lecture   files in 'c

To modify the file open the file with read and write mode

“r+” or “w+” or “a+” Generally “r+” mode is use for this purpose

1. Initialize the variable2. Open a file in read/write mode3. Read information from file4. Print it5. Check whether the information is right or wrong?1. If Wrong, accep correct information from user, move the file

pointer to the start of record or information. Re-write it that means new information into the file.

2. If not wrong, go to step 6.

6. Repeat steps 3 to 6 till file is not end.7. Stop procedure

Page 30: Mesics lecture   files in 'c

#include<stdio.h>struct stock{

int itid, qty;char n[100];float rate;

}it;

void main(){

FILE *fp; int ch; int r = 0;fp = fopen(“item.c”, “r+”);if(fp==NULL){

printf(“Unable to open item.c”);}

}

Page 31: Mesics lecture   files in 'c

else{do{

fread(&it, sizeof(it),1,fp);printf(“\n%d %s %d %f”, it.itid, it.n, it.qty, it.rate);printf(“\n Press 1 to change it?”);scanf(“%d”,&ch);

if(ch==1){

printf(“\n Enter Itemid ItemName Quantity & Price”);scanf(“%d%s%d%f”, &it.itid, it.n, &it.qty, &it.rate);fseek(fp, r*sizeof(it), 0);fwrite(&it, sizeof(it),1,fp);

}r++;}while(!feof(fp));fclose(fp);

}}

Page 32: Mesics lecture   files in 'c

fseek(FILE *fptr, long offset, int reference)

Moves the pointer from one record to another.

The first argument is the file pointer The second argument tells the compiler

by how many bytes the pointer should be moved from a particular position.

The third argument is the reference from which the pointer should be offset.

Page 33: Mesics lecture   files in 'c

fseek(FILE *fptr, long offset, int reference)

The third argument is the reference from which the pointer should be offset. SEEK_END moves the pointer from end of

file SEEK_CUR moves the pointer from the

current position SEEK_SET moves the pointer from the

beginning of the file

Page 34: Mesics lecture   files in 'c

fseek(FILE *fptr, long offset, int reference) Example

fseek(fptr, size, SEEK_CUR) sets the cursor ahead from current position by size bytes

fseek(fptr, -size, SEEK_CUR) sets the cursor back from current position by size bytes

fseek(fptr, 0, SEEK_END) sets cursor to the end of the file

fseek(fptr, 0, SEEK_SET) sets cursor to the beginning of the file

Page 35: Mesics lecture   files in 'c
Page 36: Mesics lecture   files in 'c