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

Similar documents
C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

Intermediate Programming, Spring 2017*

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

C File Processing: One-Page Summary

Ch 11. C File Processing (review)

ENG120. Misc. Topics

CS240: Programming in C

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

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

Chapter 11 File Processing

System Software Experiment 1 Lecture 7

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

Lecture6 File Processing

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

PROGRAMMAZIONE I A.A. 2017/2018

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

LAB 13 FILE PROCESSING

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

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

Lecture 9: File Processing. Quazi Rahman

LAB 13 FILE PROCESSING

Introduction to Computer Programming Lecture 18 Binary Files

Standard C Library Functions

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

Naked C Lecture 6. File Operations and System Calls

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

25.2 Opening and Closing a File

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

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

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

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

Introduction to file management

C: How to Program. Week /June/18

C PROGRAMMING. Characters and Strings File Processing Exercise

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

Standard File Pointers

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

Input/Output and the Operating Systems

C-Refresher: Session 10 Disk IO

Computer System and programming in C

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

STRUCTURES & FILE IO

Input / Output Functions

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

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

C mini reference. 5 Binary numbers 12

File IO and command line input CSE 2451

EM108 Software Development for Engineers

Computer programming

M.CS201 Programming language

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

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

C programming basics T3-1 -

Organization of a file

Program Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)

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

CS240: Programming in C

Computer Programming Unit v

Data File and File Handling

File I/O. Preprocessor Macros

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

Programming Fundamentals

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

Input/Output: Advanced Concepts

CS 261 Fall Mike Lam, Professor. Structs and I/O

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

Pointers and File Handling

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

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

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

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

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Fundamentals of Programming. Lecture 10 Hamed Rasifard

UNIX System Programming

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

BBM#101# #Introduc/on#to# Programming#I# Fall$2014,$Lecture$13$

Goals of this Lecture

C Programming Language

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

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

2009 S2 COMP File Operations

C Basics And Concepts Input And Output

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$13$

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

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS1003: Intro to CS, Summer 2008

Programming & Data Structure

Solutions to Chapter 7

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

CSCI 171 Chapter Outlines

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

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Lecture 8: Structs & File I/O

File I/O. Last updated 10/30/18

File Handling. Reference:

Transcription:

CS 2060

Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory).

Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). C views a file as a sequential stream of bytes, beginning at index zero.

Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). C views a file as a sequential stream of bytes, beginning at index zero. Files have dynamic length, meaning that they grow bigger as we add data.

FILE structure A file is represented by a FILE structure, defined in stdio.h: FILE *f = NULL; The file processing functions all use pointers to FILEs.

End-of-file marker The end of the file is marked with an end-of-file marker (EOF). 0 1 2 3 EOF Table: A file with four bytes

Opening a file To open a file, use fopen: FILE *f = fopen("hello.txt","r"); fopen returns a FILE pointer. The first argument is the file name. The second argument is the file open mode.

File open modes There are many file open modes; the most common are shown here: Mode Description Notes "r" Read-only Opens existing file "w" Write-only Creates new file, deleting old file if it exists "a" Append Begins with file pointer at end of file "r+" Read and write Opens existing file "w+" Read and write Creates new file, deleting old file if it exists

Opening a file If fopen fails to open the requested file, it will return NULL.

Opening a file // try to open file FILE *f = fopen(filename,"r"); // check if it succeeded if ( f == NULL ) { // print error message printf( "Could not open %s for reading\n", filename ); exit(1); // bail }

Opening a file fopen might fail for several reasons, e.g.: Trying to open as read-only a file that does not exist Trying to open a file at a path that is not reachable (directory does not exist) Insufficient permissions

Closing a file When we are done with the file, we need to close it with fclose.

Closing a file When we are done with the file, we need to close it with fclose. On some platforms, only a limited number of files can be open at once.

Closing a file When we are done with the file, we need to close it with fclose. On some platforms, only a limited number of files can be open at once. Opened files will be closed when your program exits.

Closing a file // open log file for appending FILE * f = fopen("log.txt","a"); //... append record to file... // close log file fclose( f );

Reading from a file Reading from a file is similar to reading from the console.

Reading from a file Reading from a file is similar to reading from the console. You can use fscanf for formatted input from a file.

Reading from a file Reading from a file is similar to reading from the console. You can use fscanf for formatted input from a file. fscanf(f,"%d",&int);

Reading from a file Reading from a file is similar to reading from the console. You can use fscanf for formatted input from a file. fscanf(f,"%d",&int); Remember to specify the file as the first argument to fscanf.

Reading from a file // Open hello.txt as read-only FILE *f = fopen("hello.txt","r"); // Read five integers from file int a[5]; for ( int i = 0; i < 5; i++ ) fscanf(f,"%d",a+i); // Close file fclose(f);

Reading characters fgetc: reads individual characters: // Open input.txt FILE *f = fopen("input.txt","r"); // Print characters from input.txt // Stop when we see end-of-file marker char c; while ( ( c = fgetc(f) )!= EOF ) putchar(c); // Close file fclose(f);

Reading characters fgets: reads a line of text: // Print lines from file // Stop when we see end-of-file marker char line[1024]; while ( 1 ) { // Read line from file char *ptr = fgets(line, 1024, f); // If result is NULL, either error occured or EOF if ( ptr == NULL ) break; } // Print line printf("%s\n",ptr);

The file pointer The FILE struct maintains a file pointer which points to where we are in the file.

Testing end-of-file feof tests if the file pointer is at the end-of-file marker: FILE *f = fopen("data.txt","r"); // Read characters until we see the end-of-file marker while (!feof(f) ) { char c = fgetc(f); putchar(c); } fclose(f);

Rewind To move the file pointer back to the beginning of the file, use rewind: FILE *f = fopen("data.txt","r"); // Read characters until we see the end-of-file marker while (!feof(f) ) { char c = fgetc(f); putchar(c); } // Rewind back to the beginning rewind(f); //...

Formatted print fprintf writes formatted data to a file (analogous to printf): // Open output.txt FILE *f = fopen("output.txt","w"); // Write out some messages fprintf(f,"hello, world!\n"); fprintf(f,"2 + 5 = %d\n", 2 + 5 ); // Close the file fclose(f);

Writing characters fputc writes individual characters: // Open input.txt and output.txt FILE *f = fopen("input.txt","r"); FILE *fout = fopen("output.txt","w"); // Copy characters from input.txt to output.txt // Stop when we see end-of-file marker char c; while ( ( c = fgetc(f) )!= EOF ) fputc(c,fout); // Close files fclose(f); fclose(fout);

Reading/writing raw data So far we have only considered text files.

Reading/writing raw data So far we have only considered text files. We can also store raw data in a file as bytes, integers, floats, etc.

Reading/writing raw data So far we have only considered text files. We can also store raw data in a file as bytes, integers, floats, etc. For example, reading/writing an integer as four bytes rather than as an ASCII string is faster and saves storage space.

Reading/writing raw data So far we have only considered text files. We can also store raw data in a file as bytes, integers, floats, etc. For example, reading/writing an integer as four bytes rather than as an ASCII string is faster and saves storage space. We can also read/write structs, etc.

Reading raw data with fread fread reads a specified number of bytes from a file: int fread( void *ptr, size_t size, size_t nitems, FILE *stream ); ptr is where the data will be written to. size is the number of bytes in one item. nitems is the number of items to read. The return value is the number of items read.

Reading integers stored as binary Reading raw integers with fread: // Open the file for reading FILE *f = fopen("integers.dat","r"); // How to read one integer from the file? int value; // Close the file fclose(f);

Reading integers stored as binary Reading raw integers with fread: // Open the file for reading FILE *f = fopen("integers.dat","r"); int value; fread( &value, sizeof(int), 1, f ); // Close the file fclose(f);

Reading integers stored as binary Reading raw integers with fread: // Open the file for reading FILE *f = fopen("integers.dat","r"); int value; if ( fread( &value, sizeof(int), 1, f )!= 1 ) { printf("read failed.\n"); } // Close the file fclose(f);

Reading integers stored as binary Reading raw integers with fread: // Open the file for reading FILE *f = fopen("integers.dat","r"); // How to read 10 integers? // Close the file fclose(f);

Reading integers stored as binary Reading raw integers with fread: // Open the file for reading FILE *f = fopen("integers.dat","r"); int values[10]; if ( fread( values, sizeof(int), 10, f )!= 10 ) { printf("read failed.\n"); } // Close the file fclose(f);

Reading a struct Reading a struct with fread: struct Point { int index, float x, float y }; //... struct Point pt; fread( &pt, sizeof(struct Point), 1, f );

Reading many structs Reading many structs with fread: struct Point { int index, float x, float y }; //... struct Point pts[10]; fread( pts, sizeof(struct Point), 10, f );

Writing raw data with fwrite fwrite writes a specified number of bytes to a file: int fwrite( void *ptr, size_t size, size_t nitems, FILE *stream ); ptr is where the data will be read from. size is the number of bytes in one item. nitems is the number of items to write. The return value is the number of items written.

Writing integers stored as binary Writing raw integers with fwrite: // Open the file for writing FILE *f = fopen("integers.dat","w"); // How to write one integer to the file? int value = 10; // Close the file fclose(f);

Writing integers stored as binary Writing raw integers with fwrite: // Open the file for writing FILE *f = fopen("integers.dat","w"); int value = 10; fwrite( &value, sizeof(int), 1, f ); // Close the file fclose(f);

Writing integers stored as binary Writing raw integers with fwrite: // Open the file for writing FILE *f = fopen("integers.dat","w"); int value; if ( fwrite( &value, sizeof(int), 1, f )!= 1 ) { printf("write failed.\n"); } // Close the file fclose(f);

Writing integers stored as binary Writing raw integers with fwrite: // Open the file for writing FILE *f = fopen("integers.dat","w"); // How to write 10 integers? int values[10] = { 0,1,2,3,4,5,6,7,8,9 }; // Close the file fclose(f);

Writing integers stored as binary Writing raw integers with fwrite: // Open the file for writing FILE *f = fopen("integers.dat","w"); int values[10] = { 0,1,2,3,4,5,6,7,8,9 }; if ( fwrite( values, sizeof(int), 10, f )!= 10 ) { printf("write failed.\n"); } // Close the file fclose(f);

Writing a struct Writing a struct with fwrite: struct Point { int index, float x, float y }; //... struct Point pt = { 0, 1.f, 1.f }; fread( &pt, sizeof(struct Point), 1, f );

Writing many structs Writing many structs with fwrite: struct Point { int index, float x, float y }; //... struct Point pts[10]; pts[0].index = 0; pts[0].x = 10; pts[0].y = 10; //... fwrite( pts, sizeof(struct Point), 10, f );

Random Access Files A random access file contains a sequence of identically-sized data records. Starting byte #: 0 100 200 300... Record #: 0 1 2 3... Table: A random access file with 100-byte records

Random Access Files Because of this structure, we can easily jump to any records without having to read through the entire file. Starting byte #: 0 100 200 300... Record #: 0 1 2 3... Table: A random access file with 100-byte records

Moving the file pointer with fseek fseek moves the file pointer to a specified location: int fseek( FILE *stream, long offset, int whence ); stream is the file offset is the offset to jump to whence indicates the reference location for the offset SEEK SET to offset from the beginning SEEK END to offset from the end SEEK CUR to offset from the current position

Random Access Files How do we calculate the offset for record n? Starting byte #: 0 100 200 300... Record #: 0 1 2 3... Table: A random access file with 100-byte records

Random Access Files Record n is at offset 100 n. Or: sizeof(struct Record)*n. Starting byte #: 0 100 200 300... Record #: 0 1 2 3... Table: A random access file with 100-byte records

Initializing a random access file /** ClientData * Stores data for a bank client */ typedef struct { unsigned int account_num; // account number char last_name[15]; // account last name char first_name[10]; // account first name double balance; // account balance } ClientData;

Initializing a random access file // Create a random access file with room for 100 records int main() { // try to open file FILE *f = fopen( "accounts.dat", "w" ); // test if file open failed (f is NULL) if (!f ) { puts("could not open accounts.dat for writing."); return 1; }

Initializing a random access file // create empty record ClientData empty_record = { 0, "", "", 0.0 }; // output 100 blank records to file for ( int i = 0; i < 100; i++ ) { fwrite( &empty_record, sizeof(clientdata), 1, f ); } } // close file fclose(f);

Initializing a random access file // create empty record ClientData empty_record = { 0, "", "", 0.0 }; // output 100 blank records to file // why not this:? fwrite( &empty_record, sizeof(clientdata), 100, f ); } // close file fclose(f);

Reading a random access file int main() { // open file (will skip failure test here for brevity) FILE *f = fopen( "accounts.dat", "r" ); // ask for record number puts("enter record number:"); int record_num = 0; scanf( "%d", &record_num );

Reading a random access file // Move file pointer to requested record fseek( f, record_num*sizeof(clientdata), SEEK_SET ); // Read requested record ClientData client_data; fread( &client_data, sizeof(clientdata), 1, f );

Reading a random access file } // Print requested record printf( "Account number: %u", client_data.account_num ) printf( "Last name: %s", client_data.last_name ); printf( "First name: %s", client_data.first_name ); printf( "Account balance: %lf", client_data.balance );