Top Banner
1 File I/O
40

File I/O

Jan 18, 2016

Download

Documents

stew

File I/O. Files. A file is an external collection of related data treated as a unit. Since the contents of primary storage are lost when the computer is shut down, we need files to store our data in a more permanent form . - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: File I/O

1

File I/O

Page 2: File I/O

2

Files• A file is an external collection of related data

treated as a unit.

• Since the contents of primary storage are lost when the computer is shut down, we need files to store our data in a more permanent form.

• Additionally, the collection of data is often too large to reside in main memory at one time. We must have the ability to read and write portions of the data while the rest remain in the file.

Page 3: File I/O

3

Classes of Files

There are two broad classes of files:Text Files: All the data are stored as

characters which must be converted to internal formats when entered into memory. Text files are organized around lines which end with a new line(“|n”).

Binary Files: Store data in internal computer formats, such as integer and floating-pt numbers. Take less time to I/O because no format conversion is necessary.

Page 4: File I/O

4

• Files are stored on auxiliary or secondary storage devices. Two most common are disk and tape.

• A buffer is a temporary storage area which holds data while they are being transferred to or from memory. Its primary purpose is to synchronize the physical devices to your program needs(e.g., more data can be input at one time then your program can use. The buffer holds extra data until you are ready for it).

Page 5: File I/O

5

• These buffering activities are taken care of by software know as device drivers or access methods, which are provided by the supplier of the Operating System you are using.

Page 6: File I/O

6

Files and Streams• The computer looks at input and output data,

whether from a physical device such as a keyboard, or from secondary files, as a stream of characters or bytes.

• Since files exist separately from our program and computer, we must have some way to connect them: we must create a linkage between the external file and its usage in our program. In C, this linkage is know as a file table.

Page 7: File I/O

7

• The term file table implies that several things are stored. It contains ALL the info needed to locate your file wherever it is stored outside of the computer. It also contains info such as the file name, the location of its file buffer, and the current state of the file.

• We define a file table with the standard FILE type. There will be a file table for each file that

our program will access.

Page 8: File I/O

8

File System Basics

• The header <stdio.h> contains:

– Three file pointers(stdin, stdout, stderr).

– Several interrelated functions.

– Each stream that is associated with a file has a file control structure of type FILE.

Page 9: File I/O

9

The file pointers(stdin, stdout, stderr-i.e., Tables) are automatically opened when the program starts.

File tables are created that POINT to these file streams.

Page 10: File I/O

10

Three File Pointers

stdin Standard input file

Connected to the keyboard

stdout Standard output file

Connected to the screen

stderr Standard error file Connected to the screen

Page 11: File I/O

11

fopen( ) Opens a file fclose( ) Closes a fileputc( ) Writes a char. to a file fputc( ) Same as putc( )getc( ) Reads a character from a file fgetc( ) Same as getc( )fgets( ) Reads a string from a filefputs( ) Writes a string to a filefseek( ) Seeks to a specified byte in a fileftell( ) Returns the current file positionfprintf( ) Is to a file what printf( ) is to the consolefscanf( ) Is to a file what scanf( ) is to the consolefeof( ) Returns true if end-of-file is reachedrewind( ) Resets the file position indicator to the begin of the fileremove( ) Erases a fileFflush() Flushes a file

Commonly used C file-system functions

Page 12: File I/O

12

The File Pointer

• In order to read or write files, your program needs to use file pointers.

• A file pointer is a pointer to a structure of type FILE.

• It points to information that defines various things about the file, including its name, status, and the current position of the file.

FILE *fp;

Page 13: File I/O

13

Opening a File • The fopen( ) function opens a stream for

use and links a file with that stream. Then it returns the file pointer associated with that file.

• General form:

FILE *fopen(const char *filename,  const char *mode);

Page 14: File I/O

14

• filename is a pointer to a string of characters that make up a valid filename and may include a path specification.

• mode determines how the file will be opened.

• fopen( ) function returns a file pointer which should not be altered by your code.

• If an error occurs when it is trying to open the file, fopen( ) returns a null pointer.

Page 15: File I/O

15

Mode Meaningr Open a text file for readingw Create a text file for writinga Append to a text filerb Open a binary file for readingwb Create a binary file for writingab Append to a binary filerr+ Open a text file for read/writew+ Create a text file for read/writea+ Append or create a text file for read/writer+b Open a binary file for read/writew+b Create a binary file for read/writea+b Append or create a binary file for read/write

Legal values for Mode

Page 16: File I/O

16

• The number of files that may be open at any one time is specified by FOPEN_MAX. This value will be at least 8.

• • If, when opening a file for read-only operations,

the file does not exist ,fopen ( ) will fail.• • When opening a file using append mode, if the

file does not exist, it will be created.

FILE *fp;if ((fp = fopen("test","w"))==NULL) {  printf(''Cannot open file.\n");  exit(1);}

Page 17: File I/O

17

When a file is opened for append:

- All new data written to the file will be

added to the end of the file.

- The original contents will remain

unchanged.

When a file is opened for writing:

- If the file does not exist, it will be

created.

- If it does exist, the contents of the

original file will be destroyed, and a

new file will be created.

Page 18: File I/O

18

• The difference between r+ and w+ is :

- r+ will not create a file if it does not exist;

however, w+ will.

- If the file already exists, opening it with w+ destroys its contents; opening it with r+ does not.

Page 19: File I/O

19

Closing a File • General form:

int  fclose(FILE *fp);

Returns zero for a successful close.

Returns EOF if an error occurs.

Generally, fclose( ) will fail only when a disk has been prematurely removed from the drive or the designated file pointer is incorrect.

Page 20: File I/O

20

• fclose( ) closes a stream that was opened

by a call to fopen( ).

• It writes any data still remaining in the

disk buffer to the file and does a formal

operating-system-level close on the file.

Page 21: File I/O

21

• Failure to close a stream invites all kinds of trouble, including :lost data, destroyed files, and possible intermittent errors in your program.

• It also frees the file control block associated with the stream, making it available for reuse.

Page 22: File I/O

22

Writing a CharacterTo a File

• putc( ) and fputc( )

• General form:

int  putc(int ch, FILE *fp);

Returns the character written if successful. Otherwise, returns EOF.

Page 23: File I/O

23

Reading a Character • getc( ) and fgetc( )

• General form:

int  getc(FILE *fp);

Returns EOF when the end of the file has been reached.

do {  ch = getc(fp);

} while(ch!=EOF);

Page 24: File I/O

24

Why have different functions(getc, fgetc, putc, fputc) that basicly perform the same?

Good question!

The answer lies in the history of “C” and involves information beyond the scope of this class.

Page 25: File I/O

25

/* KTOD: A key to disk program. */#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){  FILE *fp;  char ch;   if(argc!=2)  {    printf(''You forgot to enter the filename.\n");   exit(1);  }

KTOD TESTReads characters from the keyboard and writes them to a disk file until the user types a

dollar sign.

Page 26: File I/O

26

  if((fp=fopen(argv[1], "w"))==NULL) {    printf(''Cannot open file.\n");    exit (1);  }  

do {     ch = getchar();     putc(ch, fp);  } while  (ch !=  '$');  

fclose(fp);   return 0;}

Page 27: File I/O

27

feof( ) • General form:

int feof(FILE *fp);

Returns true if the end of the file has been reached; otherwise, returns zero.

while(!feof(fp)) ch = getc(fp);

Page 28: File I/O

28

Working with Strings • fputs( )

• General form:

int fputs(const char *str, FILE *fp);

Returns EOF if an error occurs.

Page 29: File I/O

29

• fgets( )

• General form:

char *fgets(char *str, int length, FILE *fp);

It reads a string from the specified stream until either a newline character is read or length–1 characters have been read.

Page 30: File I/O

30

If a newline is read, it will be part of the string (unlike the gets( ) function).

It returns str if successful and a null pointer if an error occurs.

Page 31: File I/O

31

rewind( )

General Format:

void rewind(FILE *fp);

Although it is most commonly used with tape files, it can be used with disk as well. It simply sets the file position indicator to the beginning of the file.

Page 32: File I/O

32

• A common use of REWIND is to change a work file from a write state to a read state.

• Often it is necessary to place data in a file temporarily for later processing.

• When all the data have been written and you are ready to begin reading, you rewind the file and simply start reading.

• You must open the file in read/write mode.

Page 33: File I/O

33

#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void){  char str[80];  FILE *fp;  

if((fp = fopen("TEST", "w+"))==NULL) {    printf("Cannot open file.\n");    exit(1);  }

Page 34: File I/O

34

  do {     printf("Enter a string (CR to quit):\n");     gets(str);     strcat(str, "\n"); /* add a newline */     fputs(str, fp);  } while(*str!='\n');  

/* now, read and display the file */  rewind(fp);  /* reset to start of file */  while(!feof(fp)) {     fgets(str, 79, fp);     printf(str);  }  return 0;}

Page 35: File I/O

35

Erasing Files

• General form:

int remove(const char *filename);

It returns zero if successful. Otherwise, it returns a nonzero value.

Page 36: File I/O

36

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

int main(int argc, char *argv[]){  char str[80];  

if(argc!=2)  {    printf(''usage: erase <filename>\n");    exit(1);  }  

Double check before erasing.

Page 37: File I/O

37

printf("Erase %s? (Y/N): ", argv[1]);

gets(str);  if(toupper(*str)= ='Y')

    if(remove(argv[1])) {      printf("Cannot erase file.\n");      exit(1);    }

return 0;

}/* END MAIN */

Page 38: File I/O

38

fprintf( ) and fscanf( )

• General form:

int fprintf(FILE *fp, const char *control_string, . .);

int fscanf(FILE *fp, const char *control_string, . ..);

fprintf(stdout, …); printf(…);

fscanf(stdin, …); scanf(…);

Page 39: File I/O

39

#include <stdio.h>#include <io.h>#include <stdlib.h>int main(void){  FILE *fp;  char s[80];  int t;  

if((fp=fopen("test", "w")) == NULL)  {    printf(''Cannot open file.\n");    exit(1);  }

Page 40: File I/O

40

  printf("Enter a string and a number: "); fscanf(stdin, "%s%d", s, &t); /* read from keyboard */   fprintf(fp, "%s %d", s, t); /* write to file */  fclose(fp);   if((fp=fopen("test","r")) == NULL) {     printf("Cannot open file.\n");     exit(1);   }  

fscanf(fp, "%s%d", s, &t); /* read from file */  fprintf(stdout, "%s %d", s, t); /* print on screen */  

return 0;}