Lecture 11 File input/output

Slides:



Advertisements
Similar presentations
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Advertisements

Text File Input and Output. Overview Text File Buffered I/O Functions fopen Function Demo of File Write and Read.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Kernel File Interface operating systems (or programming I/O in Unix)
File I/O.
 Types of files  Command line arguments  File input and output functions  Binary files  Random access.
N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
Pointers as Structure Members u One reason to use pointers in structure: struct book { float price; char title[50]; char abstract[5000]; }; …… struct book.
File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from.
Chapter 7 Files By C. Shing ITEC Dept Radford University.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
C Programming Lecture 12 : File Processing
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
Structured Programming Approach Module VIII - Additional C Data Types File Handling Prof: Muhammed Salman Shamsi.
Adv. UNIX:fp/101 Advanced UNIX v Objectives of these slides: –a more detailed look at file processing in C Special Topics in Comp. Eng.
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Advanced Programming in the UNIX Environment Hop Lee.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
Lecture 12 CIS 208 Friday, March 3rd , 2005.
External Files: Abstractly, a file can be thought of as a stream of data (either char or binary). C has two groups of files: standard files, such as stdin,
Chapter 4 File Processing
Chapter 9 – File Input Output
TMF1414 Introduction to Programming
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
CGS 3460, Lecture 41 Apr 21, 2006 Hen-I Yang
File Handling in C.
Input/Output (Continued)
CSC215 Lecture Input and Output.
CS111 Computer Programming
What you need for the 1st phase of project
File Handling in C.
Introduction to Programming
Introduction to Programming
File I/O We are used to reading from and writing to the terminal:
Lecture 15 Files.
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
Text and Binary File Processing
File Input and Output.
File Handling in C.
Henning Schulzrinne Columbia University
Fundamental of Programming (C)
File I/O & UNIX System Interface
File I/O.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Presentation transcript:

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

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

Example of file storage formats Integer 128 is stored in ASCII file as 1 2 8 <= characters 49 50 56 <= ASCII code in decimal 00110001 0110010 0111000 <= in disk, 24 bits Integer 128 in memory 0000000 1000000 Binary file in disk 00000000000000000000010000000 <= in disk, 32 bits

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

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 

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.

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

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);

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)

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);

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);

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; }

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

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

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); }

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; }