1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.

Slides:



Advertisements
Similar presentations
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.
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
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.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
1 Lecture09: Global Variables, File I/O, and Variable-Length Arguments 5/16/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Opening and Closing Files First define a file pointer, which can "pointing" to one of the opened file. #include... FILE *fp; Use fopen() to open a file,
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.
Characters and Strings File Processing Exercise C Programming:Part 3.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
File IO and command line input CSE 2451 Rong Shi.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
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.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from.
Using Files Declare a variable, called file pointer, of type FILE * Use function fopen to open a named file and associate this file with the file pointer.
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.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
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.
Files A collection of related data treated as a unit. Two types Text
 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.
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
Lecture 11 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
Input/Output (Continued)
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
What you need for the 1st phase of project
CSE1320 Files in C Dr. Sajib Datta
Programming and Data Structures
Chapter 11 – File Processing
Lecture 15 Files.
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
Text and Binary File Processing
File Input and Output.
Fundamental of Programming (C)
FILE handeling.
Module 12 Input and Output
ETE 132 Lecture 8 By Munirul Haque.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C

File I/O Before a file can be read or written, it has to be opened by the library function fopen. fopen takes an external name like data.txt, does some housekeeping and negotiation with the operating system, and returns a pointer to be used in subsequent reads or writes of the file. This pointer points to a structure FILE. FILE *fp;

Text vs. Binary Files Text files are divided into lines. Each byte in a text file represents a character, therefore readable by humans In binary files, each byte may not be a character.

File operations Open a file: fopen() Close a file: fclose() Read a binary file: fgetc(), getc(), fgets(), puts(), fscanf(), fread() Write a binary file: fputc(), putc(), fputs(), puts(), fprintf(), fwrite() File positioning: fseek(), ftell(), fgetpos(), fsetpos()

fopen() FILE *fopen(char *name, char *mode); void fclose(FILE* stream) fopen returns a pointer to a FILE. mode can be –“r” - read –“w” - write –“a” - append –“b” can be appended to the mode string to work with binary files. For example, “rb” means reading binary file.

Text Files – fprintf() int fprintf(FILE *fp, char *format,...); Similar to printf. On success, the total number of characters written is returned. If a writing error occurs, a negative number is returned.

Example – create and write to a file #include int main() { FILE *fp; char name[10]; double balance; int account; if ((fp = fopen(“clients.dat”, “w”)) == NULL) { printf(“File could not be opened\n”); } else { printf(“Enter one account, name, and balance.\n”); scanf(“%d%s%lf”, &account, name, &balance); fprintf(fp, "%d %s %.2f\n", account, name, balance); fclose(fp); } return 0; }

Text Files – fscanf() int fscanf(FILE *fp, char *format,...); Similar to scanf. On success, return the number of items successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. And, if end-of-file happens before any data could be successfully read, EOF is returned.EOF int feof(FILE *fp); return 1/0 end-of-file is reached

Text Files – read from a file #include int main() { FILE *fp; char name[10]; double balance; int account; if ((fp = fopen(“clients.dat”, “r”)) == NULL) { printf(“File could not be opened\n”); } else { fscanf(fp, “%d%s%lf”, &account, name, &balance); printf("%d %s %.2f\n", account, name, balance); fclose(fp); } return 0; }

Text Files – character I/O int fputc(int c, FILE *fp); int putc(int c, FILE *fp); Write a character c to a file. putc() is often implemented as a MACRO (hence faster). On success, the character written is returned. If a writing error occurs, EOF is returnedEOF int fgetc(FILE *fp); int getc(FILE *fp); Read a character c to a file. getc() is often implemented as a MACRO (hence faster). On success, the character read is returned. If a read error occurs, EOF is returned.EOF

Text Files – character I/O #include int main() { FILE *source_fp, *dest_fp; int ch; if ((source_fp = fopen("source.txt", "r")) == NULL) printf("cannot open source file\n"); if ((dest_fp = fopen("dest.txt", "w")) == NULL) printf("cannot open dest file\n"); while ((ch = getc(source_fp)) != EOF) putc(ch, dest_fp); fclose(source_fp); fclose(dest_fp); return 0; }

Text Files – character I/O int ugetc(int c, FILE *fp); Push back a character read from a file pointer. int feof(FILE *fp); return 1/0 end-of-file is reached

Text Files – character I/O #include int main () { FILE * fp; int c; fp = fopen ("source.txt","r"); if (fp == NULL) { printf("cannot open the file\n"); return 0; } while (!feof (fp)) { c = getc(fp); if (c == '#') fp); else putc(c, stdout); // stdout is the screen } return 0; }

Text Files – standard input & output FILE *stdin // screen input as a file FILE *stdout // screen output as a file

Text Files – stdin, stdout #include int main () { int c; while ((c = fgetc(stdin)) != '*') { fputc(c, stdout); }

In-Class Exercise 9.1 Write a program that converts all letters in a file, called “source.txt” to upper case. (Characters other than letters shouldn’t be changed) The program should obtain the file name from the command line and write its output to stdout.

Text Files – Line I/O int fputs(const char *s, FILE *fp); Write a line of characters to a file. On success, a non-negative value is returned. On error, the function returns EOF.EOF char* fgets(char *s, int n, File *fp); Read characters from a file until it reaches the first new-line or (n-1) characters, in which it places the NULL character (‘\0’) at the end of the string. On success, the function returns s. If the end-of-file is encountered before any characters could be read, the pointer returned is a NULL pointer (and the contents of s remain unchanged).

Text Files – Line I/O #include int main() { FILE *source_fp, *dest_fp; char s[100]; if ((source_fp = fopen("source.txt", "r")) == NULL) printf("cannot open source file\n"); if ((dest_fp = fopen("dest.txt", "w")) == NULL) printf("cannot open dest file\n"); while (fgets(s, 100, source_fp) != NULL) fputs(s, dest_fp); fclose(source_fp); fclose(dest_fp); return 0; }

In-Class Exercise 9.2 Write a program that reads a text file “source.txt”, counts the number of characters, the number of words, and the number of lines in this text file, and outputs these numbers on the screen.

Binary Files – fread() and fwrite() size_t fread(void *array, size_t size, size_t count, FILE *fp); size_t fwrite(void *array, size_t size, size_t count, FILE *fp); array must be a pointer size - size of elements in this array count - number of elements in this array Return the total number of elements successfully read or written.

Binary Files: read from a file #include int main() { FILE *fp; float value[3]; fp = fopen(“account.txt”, "rb"); fread(value, sizeof(float), 3, fp); printf("%f\t%f\t%f\n", value[0], value[1], value[2]); fclose(fp); return 0; }

Binary Files: write to a file #include int main() { FILE *fp; float value[3] = {1.0, 2.0, 3.0}; fp = fopen(“account.txt”, “wb"); fwrite(value, sizeof(float), 3, fp); fclose(fp); return 0; }

File positioning Every opened file has a file position for the next read or write. When a file is first opened, the file position is set at the beginning of a file. When any read or write is performed, the file position moves automatically. long int ftell(FILE *fp); Return the current file position (byte offset from the start of a file) as a long integer. int fseek(FILE *fp, long int offset, int whence); Change the current file position to offset relative to whence.

File positioning int fseek(FILE *fp, long int offset, int whence); Change the current file position to offset relative to whence. Whence can be SEEK_SET Beginning of file SEEK_CUR Current file position SEEK_END End of file

File positioning – fseek & ftell #include int main () { FILE *fp; long int size; fp = fopen ("example.txt", "r"); if (fp == NULL) printf("Error opening the file\n"); fseek(fp, 0, SEEK_END); size = ftell(fp); fclose(fp); printf("Size of example.txt: %ld bytes.\n", size); return 0; }

In-Class Exercise 9.3 #include int main() { FILE* fp; fp = fopen("example.txt", "w"); fputs("This is an apple.", fp); fseek(fp, ?, SEEK_SET); fputs(" sam", fp); fclose(fp); return 0; } Modify the left program such that the file content will be changed to “This is a sample.” Change ? with a correct offset number.