File I/O.

Slides:



Advertisements
Similar presentations
File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
Advertisements

BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
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.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
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.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
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.
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.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
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 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to 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.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
C Programming Lecture 12 : File Processing
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()”
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.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
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.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
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.
 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.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
ECE Application Programming
Lecture 11 File input/output
TMF1414 Introduction to Programming
Chapter 7 Text Input/Output Objectives
File I/O.
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
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
What you need for the 1st phase of project
CSE1320 Files in C Dr. Sajib Datta
File I/O We are used to reading from and writing to the terminal:
CSC215 Lecture Input and Output.
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
File Input and Output.
File Handling.
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
File Handling in C.
FILE handeling.
Module 12 Input and Output
ETE 132 Lecture 8 By Munirul Haque.
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Presentation transcript:

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. 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.

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.

Files are stored on auxiliary or secondary storage devices 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).

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.

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.

The term file table implies that several things are stored 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.

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.

The file pointers(stdin, stdout, stderr-i. e 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.

Three File Pointers stdin Standard input file Connected to the keyboard stdout Standard output file Connected to the screen stderr Standard error file

Commonly used C file-system functions fopen( ) Opens a file fclose( ) Closes a file putc( ) 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 file fputs( ) Writes a string to a file fseek( ) Seeks to a specified byte in a file ftell( ) Returns the current file position fprintf( ) Is to a file what printf( ) is to the console fscanf( ) Is to a file what scanf( ) is to the console feof( ) Returns true if end-of-file is reached rewind( ) Resets the file position indicator to the begin of the file remove( ) Erases a file Fflush() Flushes a file

The File Pointer FILE *fp; 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;

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

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.

Legal values for Mode Mode Meaning r Open a text file for reading w Create a text file for writing a Append to a text filer b Open a binary file for reading wb Create a binary file for writing ab Append to a binary filer r+ Open a text file for read/write w+ Create a text file for read/write a+ Append or create a text file for read/write r+b Open a binary file for read/write w+b Create a binary file for read/write a+b Append or create a binary file for read/write

FILE *fp; if ((fp = fopen("test","w"))==NULL) {   printf(''Cannot open file.\n");   exit(1); } 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.

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.

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.

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.

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.

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.

Writing a Character To a File putc( ) and fputc( ) General form: int  putc(int ch, FILE *fp); Returns the character written if successful. Otherwise, returns EOF.

Reading a Character do { ch = getc(fp); } while(ch!=EOF); 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);

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.

/. KTOD: A key to disk program. / #include <stdio /* 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 TEST Reads characters from the keyboard and writes them to a disk file until the user types a dollar sign.

if((fp=fopen(argv[1], "w"))==NULL) { printf(''Cannot open file   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; }

feof( ) while(!feof(fp)) ch = getc(fp); 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);

Working with Strings fputs( ) General form: int fputs(const char *str, FILE *fp); Returns EOF if an error occurs.

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.

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.

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.

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.

#include <stdio. h> #include <stdlib #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);   }

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

Erasing Files General form: int remove(const char *filename); It returns zero if successful. Otherwise, it returns a nonzero value.

Double check before erasing. #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.

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 */

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

#include <stdio. h> #include <io. h> #include <stdlib #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);   }

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