File Handling

Post on 10-Feb-2016

218 views 0 download

Tags:

description

CPP213

Transcript of File Handling

FILE HANDLING

In order to use files we have to learn about File I/O i.e. how to write information to a file and how to read information from a file.

We will see that file I/O is almost identical to the terminal I/O that we have being using so far.

The primary difference between manipulating files and doing terminal I/O is that we must specify in our programs which files we wish to use.

FILE *fp;File pointer points to a

structure that contains about the file, such as the location of a buffer, the character position in the buffer, whether the file is being read or written, and whether errors or end of file have occurred.

fp=fopen("d:\\sample.txt","w");fopen is a library function

used before reading and writing a file.

FILE *fopen(char *name, char *mode)– name – is a character

string containing the name of the file.

– mode – a character string, which indicates how one intends to use the file.

int fclose(FILE *fp);

fclose is the inverse of fopen, it breaks the connections between the file pointer and the external name that was established by fopen, freeing the file pointer for another file.

MODE“r”open text file for reading“w” write text file for writing; discard previous contents

if any“a” append; open or create text file for writing at end

of file“r+” open text file for update (i.e. reading and writing)“w+” create text file for update, discard previous

contents if any“a+” append; open or create text file for update, writing

at endUpdate mode permits reading and writing the same file

int fputc(int c, FILE *fp);fputc write the

character c to the file and returns the character written, or EOF if an error occurs.

Writing to a file

int fgetc(FILE *fp);fgetc returns the next

character from the stream referred to by file pointer (fp); it returns EOF for end of file or error.

Reading from a file

 

int fgetc(FILE *fp);

Appending to a file

 

ASCII Table (reference)

File Line Input and Output

int fputs(char *line, FILE *fp)fputs writes a string

(which need not contain a newline) to a file it returns EOF if an error occurs, and non negative otherwise.

Writing

 

char *fgets(char *line, int maxline, FILE *fp)fgets reads the next input

line from file pointer (fp) into the character array line. The resulting line is terminated by ‘\0’.

Reading

 

Formatted Input and Output Files

int fprintf(FILE *stream, const char *format, …)fprintf converts and writes

output to stream under the control of format.

Writing

 

int fscanf(FILE *stream, const char *format, …)• fscanf reads from stream

under control of format, and assign converted values through subsequent arguments, each of which must be a pointer.

Reading

 

END..