Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 11 File input/output

Similar presentations


Presentation on theme: "Lecture 11 File input/output"— Presentation transcript:

1 Lecture 11 File input/output
1. Concepts of file I/O 2. File I/O in C 3. File I/O functions in stdio library

2 1. Concepts file I/O File I/O is a big deal in OS.
File output is to save data from memory to files in disk or other media for long term storage File input is to open files in disk and load file data into memory for processing ASCII file and Binary file formats ASCII (or text file) stores data as a sequence of characters Binary file store data as it is in memory

3 Example of file storage formats
Integer 128 is stored in ASCII file as <= characters <= ASCII code in decimal <= in disk, 24 bits Integer 128 in memory Binary file in disk <= in disk, 32 bits

4 File I/O: data in memory buffer disk
Output text file Output buffer Disk Stream file input/ouput Input buffer Input text file Memory

5 2. File input/output with C
ANSI C provides standard library functions for file I/O Use a file structure to hold the information of an I/O file. Defined in stdio.h typedef struct  {        int             level;       /* fill/empty level of buffer */        unsigned        flags;       /* File status flags          */        char            fd;          /* File descriptor            */        unsigned char   hold;        /* Ungetc char if no buffer   */        int             bsize;       /* Buffer size                */    unsigned char   *buffer;     /* Data transfer buffer       */    unsigned char   *curp;       /* Current active pointer     */        unsigned        istemp;      /* Temporary file indicator   */        short           token;       /* Used for validity checking */ }   FILE;  FILE * fp; // declare a file pointer 

6 fopen() FILE *fopen(const char *filename, const char *mode); Mode: r or rb Open file for reading. w or wb Truncate to zero length or create file for writing. a or ab Append; open or create file for writing at end-of-file. r+ or rb+ or r+b Open file for update (reading and writing). w+ or wb+ or w+b Truncate to zero length or create file for update. a+ or ab+ or a+b Append; open or create file for update, writing at end-of-file.

7 File write example #include <stdio.h> int main() { FILE *fp = fopen("test.txt", "w"); if (fp == NULL) { perror("Error reading file"); return 0; } int x = 10; fprintf(fp, "Hello\n"); //write text to the file fprintf(fp, "int x=%d\n", x); //formatted write fclose(fp); //close the stream, changes are saved

8 Example of file read #include <stdio.h> int main(void) { FILE *fp; int c; fp = fopen("test.txt", "r"); if (fp == NULL) { perror("Error reading file"); return 0; } while((c = fgetc(fp)) != EOF) { putchar(c); fclose(fp);

9 3. File I/O functions (check stdio library)
File input: char fgets (char *restrict str, int size, FILE * restrict stream) int fgetc(FILE *stream) size_t fread (void * Buffer, size_t Size, size_t Count, FILE * Stream) fscanf(FILE *stream, const char *format, variable addresses…) rewind(FILE *stream) int fseek(FILE *stream, long int offset, int whence) File output int fputc(int char, FILE *stream) int fputs(const char *str, FILE *stream) int fprintf(FILE *stream, const char *format, ...) size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

10 Read string by fgets() char buf[100]; #include <stdio.h>
int main() { char buf[100]; FILE *fp = fopen("test.txt", "r"); if (fp == NULL) { perror("Error reading file"); return 0; } fgets(buf, sizeof(buf), fp); puts(buf); fclose(fp);

11 Read strings #include <stdio.h> int main(int argc, char *argv[]) { FILE *fp; char buf[128]; if ( (fp=fopen("test.txt", "r") ) == NULL ) { printf("Cannot open file.\n"); return 0; } while( !feof(fp) ) { if( fgets(buf, sizeof(buf), fp) ) printf("%s", buf); fclose(fp);

12 Example of fprintf(), fscanf() and rewind()
#include <stdio.h> int main () { char str[80]; float f; FILE *fp = fopen("test.txt","w+"); if (fp == NULL) { perror("Error opening file"); return 0; } fprintf(fp, "%f %s", 3.14, "PI"); //write to file rewind(fp); // move the pointer to the beginning fscanf(fp,"%f %s", &f, str); // formatted read from file fclose(fp); printf("%f and %s are added.\n", f, str); return 0; }

13 fseek(), rewind() int fseek(FILE *stream, long offset, int whence); whence to one of three things: SEEK_SET offset is relative to the beginning of the file SEEK_CUR offset is relative to the current file pointer position SEEK_END offset is relative to the end of the file. Examples fseek(fp, 100, SEEK_SET); // seek to the 100th byte of the file fseek(fp, -30, SEEK_CUR); // seek backward 30 bytes from the current position fseek(fp, -10, SEEK_END); // seek to the 10th byte before the end of file void rewind(FILE *stream); rewind(fp); // seek to the beginning of the file

14 fseek(), fputs() #include <stdio.h>
int main() {        FILE *fp = fopen(“test.txt", "w");        fputs("Hello World", f);        fseek(f, 6, SEEK_SET);        fputs(“C programmer", fp);        fclose(fp);        return 0; } In file test.txt Hello C programmer

15 fwrite, fread and fseek #include <stdio.h> #include <string.h> int main() { FILE *fp; char c[] = "this is a test on fwrite, fread and fseek"; char buffer[100]; fp = fopen("file.txt", "w+"); /* Open file for both reading and writing */ fwrite(c, strlen(c) + 1, 1, fp); /* Write data to the file */ fseek(fp, 0, SEEK_SET); /* Seek to the beginning of the file */ fread(buffer, strlen(c)+1, 1, fp); /* Read and display data */ printf("%s\n", buffer); fclose(fp); return(0); }

16 fgetc() or getc(), with rewind()
  /* show it once */   while(!feof(fp))     putchar(fgetc(fp));   rewind(fp);   /* show it twice */   while(!feof(fp))     putchar(getc(fp));   fclose(fp);   return 0; } #include <stdio.h> int main(int argc, char *argv[]) { FILE *fp;  if((fp = fopen(“test.txt”, "r"))==NULL) { printf("Cannot open file.\n"); return 0; }


Download ppt "Lecture 11 File input/output"

Similar presentations


Ads by Google