38
FILES Files types and operations

FILES

  • Upload
    channer

  • View
    23

  • Download
    0

Embed Size (px)

DESCRIPTION

FILES. Files types and operations. Files. Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides in a directory The path is the directory to get to the file. Each file in a directory has a unique filename. File Actions. - PowerPoint PPT Presentation

Citation preview

Page 1: FILES

FILES

Files types and operations

Page 2: FILES

Files Files are used to store data Data can be

Text (ASCII only: 0 127) Binary (Full range: 0 256)

Each file resides in a directory The path is the directory to get to the file. Each file in a directory has a unique

filename.

Page 3: FILES

File Actions Files can be

Written Read Appended (Added)

Files need to be identified before operating on them (path/filename)

Many files can be opened at the same time!

Page 4: FILES

Using Files

Indicate the file to use and how you want to use it path/filename or filename read/write/append

Perform the write or read operation Indicate you have finished using the file.

Page 5: FILES

Book Analogy – Choose and open book

You can think of using files in the same way that you would use a book from your bookshelf at home.

In order to use a book (read from it or write to it), you must first open the book. This involves using the name of the book to find it amongst the other books on the bookshelf. Also the type of book you will get will depend upon whether you want to read it (printed text only eg text book) or write to it (blank pages eg note book).

- This is the same as opening a file.

Page 6: FILES

Book Analogy – Bookmark position

Once you have the book you will want to identify the book and where you are in the book using a bookmark. If you have more than one book then you will use more than one bookmark.

- This is the same as the file pointer.

You can read from the book or write to the book you have chosen. This means that you must use the bookmark to identify both the book and the page in the book you are using.

- This is the same since all file access requires a file pointer.

Page 7: FILES

Book Analogy – Close Book

Once you have finished using the book, you will close the book and put it back on the book. You can then put the bookmark away.

- This is the same as closing the file. Any data will be written to the file when it is closed.

Page 8: FILES

Text Files

Text files are used to store ASCII data.

Text files consist of ASCII data and a special end of file marker to show the end of the file.

ctrl-Z in Windows (Ascii character 26)

ctrl-D in UNIX (Ascii character 4)

ASCII Text <EOL>

ASCII Text <EOL>

ASCII Text<EOL>

ASCII Text<EOL>

Sample of an ASCII file! <EOL>

ASCII Text <EOL>

<EOF>

Page 9: FILES

Text Files

File operations require special Input/Output routines which can be found in <stdio.h>

More than one file can be used at the same time in a program.

Each file needs to be identified by it’s own file pointer.

A file pointer is used by the OS to keep track of the operations upon the file.

Page 10: FILES

File Pointers in C

Each file is referred to by a special variable called a file pointer.

eg FILE *fp ; One file pointer is used per file. Therefore if more than one

file is to be used, then more than one file pointer must be declared.

eg FILE *fp_in, *fp_out ; The file pointer is assigned when the file is opened for use.

This requires the use of the fopen() function. The open function requires the filename and how the file is to be accessed (read, write, read/write etc).

Page 11: FILES

Text Files

The file data can be accessed using fgetch(), fprintf(), fscanf(), fgets(). These are same as the I/O functions you are familiar with, except they require a file pointer. The characters in the file are read sequentially.

The file pointer is deassigned when you close a file. If you have written any data to the file, the file will be updated when the file is closed.

Page 12: FILES

Opening Files – fopen()

Files are opened using fopen()fopen(filename, mode)

filename is a string containing the name of the file to be opened. mode is a string stating how the file is to be used

“r” read only text file “w” write only text file “rw” read and write text file “a” appending text file. Writes to the end of the file. “rb” read binary file. “wb” write binary file. “rwb” read & write binary file

• fopen() returns the file pointer if the file could be opened. fopen() returns a NULL if the file could not be opened. If the

happens end the program with exit(-1).

Page 13: FILES

Example of fopen()

#include <stdio.h>#include <stdlib.h>

int main(void){FILE *in ; /* declare the input file pointer */if ( (in = fopen("icp.txt","r")) == NULL) {// display message and reason for failure

perror("Error: Cannot open file icp.txt") ; exit(-1) ;

}}

Page 14: FILES

Another example of fopen()

#include <stdio.h>#include <stdlib.h>

int main(void){FILE *in ; /* declare the input file pointer */char filename[80] ;

char error_msg[80] ;

printf("Please enter the file to open"); scanf("%s",filename) ;

if ( (in = fopen(filename,"r")) == NULL) {// display message and reason for failure with filenamesprintf(error_msg,"Error: Cannot open file %s",filename);

perror(error_msg) ; exit(-1) ;

}}

Page 15: FILES

Closing Files

Files are closed using the fclose() function.fclose(file_pointer)

where file_pointer is the file_pointer returned from fopen().

Page 16: FILES

Data Access

The data is accessed with functions similar to the ones you have used before to get data from the keyboard.

The file access functions are fprintf(), fscanf(), fgetc(), fputc(), fgets(), fputs().

The file access functions have a f prefix and must have a file pointer as an argument. The file pointer is used to identify the file to be accessed.

All access is performed sequentially. The file access function automatically take into account the position in the file.

The file access function prototypes are found in <stdio.h>

Page 17: FILES

End of File

The file is marked by an end of file character.

EOF is a #define in the <stdio.h> used to denote the End Of File character.

When the end of file is reached character input functions return EOF character string input functions return a NULL pointer scanf() function returns EOF

A feof() function can be used to determine whether the end of the file has been reached. This means that the EOF must have already been read by one of the input functions. This must be used with binary files.

Page 18: FILES

Data Access FunctionsFunction Description Returns

fgetc(file_pointer) Read a character from the file. Char read from the file.EOF if end of file.

fputc(character, file_pointer) Write a character from the file. Character written.

fgets(string_name, n, file_pointer) Read n-1 characters from the fileand store in the string. Reada line of text from the file.

Pointer to the string.NULL for end of file

fputs(string_name, file_pointer) Write the string to the file. True value if write ok.False value if write

failed.

fscanf(file_pointer,”controlstring”,vars)

Similar to scanf except that itreads from a file rather thanfrom the keyboard.

EOF on the end of file.

fprintf(file_pointer,”controlstring”,vars)

Similar to printf except that itwrites to a file rather thandisplays on the screen.

The number of byteswhich have beenprinted.

Page 19: FILES

End of File

Syntax:feof(file_pointer)

where file_pointer is used as a marker to indicate the file

you are working with. For each file there must be a new file pointer.

Returns true, if End Of File has been found otherwise

returns false.

Page 20: FILES

Reading Files

The basic sequence for reading a file is

declare file pointeropen the fileWHILE (NOT the end of the file)

read data from file process the data

close the file

Page 21: FILES

Writing Files

The basic sequence for writing a file is

declare file pointeropen the file

write the data to the file

close the file

Page 22: FILES

Using the File Pointer with Functions

The file pointer is declared as FILE *name ; in the program.

When declaring a file pointer in the function definition, the declaration for the file pointer is

FILE *local_name

In the prototype use FILE * as the data type of the file pointer.

When calling a function with the file pointer, just use the name of the file_pointer

Page 23: FILES

Example to write 99 to a file

#include <stdio.h>#include <stdlib.h>

void fn(FILE *) ; /* prototype */

int main(void){FILE *fp ;

/* open the file */if ( (fp = fopen("file.txt","w")) == NULL) {

perror("Error: Cannot open File file.txt") ;exit(-1) ;

}

fn(fp) ; /* call the function */fclose(fp) ; /* close the file */}

Page 24: FILES

Example (cont)

/* function with the file_pointer passed as an argument */

void fn(FILE *file_pointer){ int value ; value = 99 ; fprintf(file_pointer, "%d", value ) ;}

Page 25: FILES

Program to print the contents of a text file

#include <stdio.h>#include <stdlib.h>

int main(void){char line[81] ; /* line to read from file */FILE *in ; /* declare the input file pointer */

/* open the file */if ( (in = fopen("file.txt","r")) == NULL) {

perror("Error: Cannot open File file.txt") ;exit(-1) ;

}/* read and print the contents of the file */while (fgets(line,81,in) != NULL) /* NULL means EOF */

printf("%s",line) ;

/* close the file */fclose(in) ;}

Page 26: FILES

Example to read & display a stock list

This program will read a list of stock from a file and display the contents in the required format.

The user must be asked for the filename

File Format Output Formatdescription price\n description $price\n

Eg Egflour 1.25 flour $1.25stamps 1.50 stamps $1.50dvd 18.23 dvd $18.23

Page 27: FILES

Example (cont)

#include <stdio.h>#include <stdlib.h>

int main(void){ char line[81] ; /* line to read from file */ char fname[40] ; /* file name */ char descript[10] ; /* description of item */ float price ; /* cost of item */

FILE *in ; /* declare the input file pointer */

/* get the filename from the user */ printf("Enter the filename ") ; scanf("%s",fname) ;

Page 28: FILES

Example (cont)

/* open the file */if ( (in = fopen(fname,"r")) == NULL) {

perror("Error: Cannot open File") ;exit(-1) ;

}

/* print the contents of the file */while (fscanf(in,"%s %g",descript,&price)!= EOF) /*check the EOF reached */ printf("%s $%.2g\n",descript,price) ;

/* close the file */fclose(in) ;}

Page 29: FILES

Example to display file contents in Ucase

#include <stdio.h>#include <ctype.h>#include <stdlib.h>

int main(void){char fname[40] ; /* file name */char ch ; /* character to read*/FILE *in ; /* declare the input file pointer */

printf("Enter the filename ") ; /* get filename from user */scanf("%s",fname) ;

/* open the file */if ( (in = fopen(fname,"r")) == NULL) { perror("Error: Cannot open File") ; exit(-1) ;}

Page 30: FILES

Example (cont)

/* print the contents of the file in uppercase*/

while ( (ch = fgetc(in)) != EOF) /*check for EOF */ printf("%c",toupper(ch)) ;

/* close the file */fclose(in) ;}

Page 31: FILES

Example to write a price list to a file

#include <stdio.h>#include <stdlib.h>

int main(void){char fname[40] ; /* file name */int j ; /* loop counter */float price[ ] = {39.95, 3.22,1.03} ; /* list of prices */FILE *out ; /*declare the output file pointer */

/* get the filename from the user */printf("Enter the filename ") ;scanf("%s",fname) ;

Page 32: FILES

Example (cont)

/* open the file */if ( (out = fopen(fname,"w")) == NULL) { perror("Error: Cannot open File") ; exit(-1) ;}

/* write the prices to the file */for (j = 0 ; j < 3; j++) fprintf(out, "%g",price[j]) ;

/* close the file */fclose(out) ;}

Page 33: FILES

Binary Files

Text files contain bytes that contains ASCII Values. Text files contain human readable information.

Binary files contain bytes that are between 0 and 255. Binary files typically are executables, wav files, picture formats, mp3, mpegs etc. There area a lot of proprietary formats that are binary.

Binary files do not have an EOF character (marker) since the EOF is equally likely to occur as part of the binary data as any other value.

The OS stores the filesize as part of its File Allocation Tables (FAT / inode).

Therefore you must use feof() to determine when the end of file has been reached.

Page 34: FILES

Binary Files

For binary files, you should only use fgetc() to read the binary character.

Other reading functions eg fscanf() are designed only to work with text files.

For binary files, you should only use fputc() to write the binary character.

Other writing functions eg fprintf() are designed only to work with text files.

Page 35: FILES

Reading Files

The basic sequence for reading a binary file is

declare file pointeropen the fileWHILE (NOT feof() )

read the byte from the file using fgetc(fp) process the data

close the file

Page 36: FILES

Writing Files

The basic sequence for writing a binary file is

declare file pointeropen the file

write the byte to the file using fputc()

close the file

Page 37: FILES

Example to read binary and display in hex

#include <stdio.h>#include <ctype.h>#include <stdlib.h>

int main(void){char fname[40] ; /* file name */unsigned char ch ; /* character to read*/FILE *in ; /* declare the input file pointer */

printf("Enter the filename ") ; /* get the filename from the user */scanf("%s",fname) ;

/* open the binary file for read*/if ( (in = fopen(fname,"rb")) == NULL) { perror("Error: Cannot open File") ; exit(-1) ;}

Page 38: FILES

Example

/* print the contents of the file in hexadecimal – space separated*/

while ( !feof(in) ) { /* check for EOF */ ch = fgetc(in); printf("%x ",ch) ;}

/* new line */printf("\n") ;

/* close the file */fclose(in) ;}