Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Similar documents
Data File and File Handling

M.CS201 Programming language

EM108 Software Development for Engineers

File Handling. Reference:

System Software Experiment 1 Lecture 7

PROGRAMMAZIONE I A.A. 2017/2018

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

UNIX System Programming

25.2 Opening and Closing a File

CSI 402 Lecture 2 Working with Files (Text and Binary)

Input/Output and the Operating Systems

HIGH LEVEL FILE PROCESSING

Standard File Pointers

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Input / Output Functions

2009 S2 COMP File Operations

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Computer Programming Unit v

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

File (1A) Young Won Lim 11/25/16

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

File IO and command line input CSE 2451

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Standard I/O in C, Computer System and programming in C

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

CS240: Programming in C

File I/O. Preprocessor Macros

C-Refresher: Session 10 Disk IO

UNIT IV-2. The I/O library functions can be classified into two broad categories:

File I/O. Arash Rafiey. November 7, 2017

File Access. FILE * fopen(const char *name, const char * mode);

Introduction to file management

CSI 402 Lecture 2 (More on Files) 2 1 / 20

Fundamentals of Programming. Lecture 10 Hamed Rasifard

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

Computer programming

C Programming Language

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

ENG120. Misc. Topics

Standard C Library Functions

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

System Programming. Standard Input/Output Library (Cont d)

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

Naked C Lecture 6. File Operations and System Calls

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Lecture 9: File Processing. Quazi Rahman

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

fopen() fclose() fgetc() fputc() fread() fwrite()

Chapter 12. Files (reference: Deitel s chap 11) chap8

UNIT- 2. Binary File

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C File Processing: One-Page Summary

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

Ch 11. C File Processing (review)

C Basics And Concepts Input And Output

Computer System and programming in C

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

C Programming 1. File Access. Goutam Biswas. Lect 29

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Lecture6 File Processing

Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Programming Fundamentals

Week 9 Lecture 3. Binary Files. Week 9

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C

Chapter 11 File Processing

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C

Engineering program development 7. Edited by Péter Vass

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING UNIT-1

Intermediate Programming, Spring 2017*

File and Console I/O. CS449 Spring 2016

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

Exercise Session 3 Systems Programming and Computer Architecture

Princeton University Computer Science 217: Introduction to Programming Systems. I/O Management

Operating System Labs. Yuanbin Wu

Princeton University. Computer Science 217: Introduction to Programming Systems. I/O Management

Princeton University Computer Science 217: Introduction to Programming Systems I/O Management

File System User API

Computer Programming: Skills & Concepts (CP) Files in C

Organization of a file

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

C PROGRAMMING. Characters and Strings File Processing Exercise

How do we define pointers? Memory allocation. Syntax. Notes. Pointers to variables. Pointers to structures. Pointers to functions. Notes.

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b =

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

structs as arguments

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

Transcription:

Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data files Unformatted data files Filename Filenames are used when dealing with disk files A filename in a C program also can contain path information. The path specifies the drive and/or directory (or folder) where the file is located. To refer c:\data\list.txt Declare the filename as char *filename = "c:\\data\\list.txt"; Opening a File The process of creating a stream linked to a disk file is called opening the file When you open a file, it becomes available for Reading (meaning that data is input from the file to the program), Writing (meaning that data from the program is saved in the file), or both When you're done using the file, you must close it To open a file, you use the fopen() library function FILE *fopen(const char *filename, const char *mode); fopen() returns a pointer to type FILE, which is a structure The argument filename is the name of the file to be opened The argument mode specifies the mode in which to open the file mode controls whether the file is binary or text and whether it is for reading, writing, or both Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. w a Opens the file for writing. If a file of the specified name doesn't exist, it is created. If a file of the specified name does exist, it is deleted without warning, and a new, empty file is created. Opens the file for appending. If a file of the specified name doesn't exist, it is created. If the file does exist, new data is appended to the end of the file. r+ Opens the file for reading and writing. If a file of the specified name doesn't exist, it is created. If the file does exist, new data is added to the beginning of the file, overwriting existing data. w+ Opens the file for reading and writing. If a file of the specified name doesn't exist, it is created. If the file does exist, it is overwritten.

a+ Opens a file for reading and appending. If a file of the specified name doesn't exist, it is created. If the file does exist, new data is appended to the end of the file. The default file mode is text. To open a file in binary mode, you append ab to the mode argument. Thus, a mode argument of a would open a text-mode file For appending, ab would open a binary-mode file for appending. FILE *fp ; fp = fopen( myfile.dat, r ); Writing and Reading File Data Program that uses a disk file can write data to a file, read data from a file, or a combination of the two You can read/write data to or from a disk file in three ways formatted input/output character input/output direct input/output Formatted File Input and Output Formatted File Output Formatted file output is done with the library function fprintf(). int fprintf(file *fp, char *fmt,...); The first argument is a pointer to type FILE The second argument is the format string. The final argument takes variable number of arguments. fprintf() works just like printf(), except that it sends its output to the stream specified in the argument list. Example: for (count = 0; count < 5; count++) { fprintf(fp, "\ndata[%d] = %f", count, data[count]); fprintf(stdout, "\ndata[%d] = %f", count, data[count]); } For formatted file input, use the fscanf() library function fscanf() is used like scanf(), except that input comes from a specified stream instead of from stdin int fscanf(file *fp, const char *fmt,...); The argument fp is the pointer to type FILE returned by fopen() fmt is a pointer to the format string that specifies how fscanf() is to read the input Third argument gives the addresses of the variables where fscanf() is to assign the input fscanf(fp, "%f %f %f %f %f", &f1, &f2, &f3, &f4, &f5); Character Input and Output

Character I/O refers to single characters as well as lines of characters Use character I/O with text-mode files Character Input Functions getc() & fgetc() for single characters fgets() for lines getc() and fgetc() Functions They input a single character from the specified stream int getc(file *fp); The argument fp is the pointer returned by fopen() when the file is opened The function returns the character that was input or EOF on error getc() and fgetc() return a single character, which is prototyped to return a type int Character Input (Contd..) The fgets() Function To read a line of characters from a file, use the fgets() library function char *fgets(char *str, int n, FILE *fp); The argument str is a pointer to a buffer in which the input is to be stored n is the maximum number of characters to be input fp is the pointer to type FILE fgets() reads characters from fp into memory, starting at the location pointed to by str Characters are read until a newline is encountered or until n-1 characters have been read Character Output putc() function and fputs() function putc() function o putc() writes a single character to a specified stream o int putc(int ch, FILE *fp); o argument ch is the character to output o argument fp is the pointer associated with the file o putc() returns the character just written if successful or EOF if an error occurs The fputs() Function putc() writes a line of characters to a stream It works just like puts(). The only difference is that with fputs() you can specify the output stream. Also, fputs() doesn't add a newline to the end of the string char fputs(char *str, FILE *fp); argument str is a pointer to the null-terminated string to be written argument fp is the pointer associated with the file The string pointed to by str is written to the file, minus its terminating \0 returns a nonnegative value if successful or EOF on error

Direct File Input and Output Direct I/O is used only with binary-mode files o With direct output, blocks of data are written from memory to disk o For example, a single direct-output function call can write an entire array of type double to disk, and a single direct-input function call can read the entire array from disk back into memory direct I/O functions are fread() and fwrite() The fwrite() Function Writes a block of data from memory to a binary-mode file int fwrite(void *buf, int size, int count, FILE *fp); argument buf is a pointer to the region of memory holding the data to be written to the file. Pointer type is void; it can be a pointer to anything o Argument size specifies the size, in bytes, of the individual data items o count specifies the number of items to be written o argument fp is the pointer to type FILE o It returns the number of items written on success; if the value returned is less than count, it means that an error has occurred To write a single type double variable x to a file, use the following: fwrite(&x, sizeof(double), 1, fp); To write an array data[ ] of 50 structures of type address to a file, two options are there: fwrite(data, sizeof(address), 50, fp); fwrite(data, sizeof(data), 1, fp); The fread() Function reads a block of data from a binary-mode file into memory Prototype is int fread(void *buf, int size, int count, FILE *fp); _argument buf is a pointer to the region of memory that receives the data read from the file. Pointer type is void argument size specifies the size, in bytes, of the individual data items being read count specifies the number of items to read argument fp is the pointer to type FILE It returns the number of items read; this can be less than count if end-of-file was reached or an error occurred fread(array2, sizeof(int), SIZE, fp);

Closing and Flushing Files :- When you're done using a file, you should close it using the fclose() function Prototype is int fclose(file *fp); _argument fp is the FILE pointer associated with the Stream returns 0 on success or -1 on error When you close a file, the file's buffer is flushed (written to the file). You can also close all open streams except the standard ones (stdin, stdout, stdprn, stderr, and stdaux) by using the fcloseall() function fcloseall() function Its Prototype is int fcloseall(void); flushes any stream buffers and returns the number of streams closed. When a program terminates, all streams are automatically flushed and closed To flush a stream's buffers without closing it, use fflush() or flushall() Use fflush() when you want a file's buffer to be written to disk while still using the file. Use flushall() to flush the buffers of all open streams. The prototypes are int fflush(file *fp); int flushall(void); argument fp is the FILE pointer If a file was opened for writing, fflush() writes its buffer to disk. If the file was opened for reading, the buffer is cleared. The function fflush() returns 0 on success or EOF if an error occurred. The function flushall() returns the number of open streams Sequential Versus Random File Access: - Every open file has a file position indicator associated with it The position indicator specifies where read and write operations take place in the file When a new file is opened, the position indicator is always at the beginning of the file, position 0 When an existing file is opened, the position indicator is at the end of the file if the file was opened in append mode, or at the beginning of the file if the file was opened in any other mode By controlling the position indicator, you can perform random file access The ftell() and rewind() Functions :- To set the position indicator to the beginning of the file, rewind() is used Its prototype is void rewind(file *fp); _The argument fp is the FILE pointer associated with the stream. _After rewind() is called, the file's position indicator is set to the beginning of the file (byte 0)

rewind(fp); ftell() is used to determine the value of a file's position indicator Its prototype is long ftell(file *fp); _argument fp is the FILE pointer _returns a type long that gives the current file position in bytes from the start of the file (first byte is at position 0) _If an error occurs, ftell() returns -1L (a type long -1) filepos = ftell(fp) ; The fseek() Function:-Using fseek(), you can set the position indicator anywhere in the file. Its prototype is int fseek(file *fp, long offset, int origin); argument fp is the FILE pointer associated with the file. The distance that the position indicator is to be moved is given by offset in bytes. fseek() returns 0 if the indicator was successfully moved or nonzero if an error occurred Constant Value Description SEEK_SET 0 Moves the indicator offset bytes from the beginning of the file. SEEK_CUR 1 Moves the indicator offset bytes from its current position. SEEK_END 2 Moves the indicator offset bytes from the end of the file Example: if ( (fseek(fp, (offset*sizeof(int)), SEEK_SET))!= 0) { fprintf(stderr, "\nerror using fseek()."); exit(1); } Detecting the End of a File :-function feof(), which can be used for both binary- and textmode files: Prototype is int feof(file *fp); The argument fp is the FILE pointer The function feof() returns 0 if the end of file hasn't been reached, or a nonzero value if end of file has been reached Deleting a File: - remove() function is used to delete the file Its prototype is int remove( const char *filename ); The variable *filename is a pointer to the name of the file to be deleted if ( remove(filename) == 0) printf("the file %s has been deleted.\n", filename); else fprintf(stderr, "Error deleting the file %s.\n",filename);

Renaming a File The rename() function changes the name of an existing disk file Its prototype is int rename( const char *oldname, const char *newname ); _The function rename() returns 0 on success, or -1 if an error occurs if ( rename( oldname, newname ) == 0 ) printf("%s has been renamed %s.\n", oldname, newname); else fprintf(stderr, "An error has occurred %s.\n", oldname); Assignment 1. How can I insert or delete a line (or record) in the middle of a file? 2. How can I recover the file name using its file descriptor? 3. How can I delete a file? How do I copy files? How can I read a directory in a C program? 4. Whats the use of fopen(), fclose(), fprintf(), getc(), putc(), getw(), putw(), fscanf(), feof(), ftell(), fseek(), rewind(), fread(), fwrite(), fgets(), fputs(), freopen(), fflush(), ungetc()? 5. How to check if a file is a binary file or an ascii file?