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

Size: px
Start display at page:

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

Transcription

1 Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008

2 Last lecture: File I/O Low-Level I/O: Schedule for Today 2 Unbuffered I/O and control functions on file descriptors. Filesystem Interface: Functions for operating on directories and for manipulating file attributes such as access modes and ownership. Today: Standard I/O Library Standard I/O library (ISO C) aka I/O on streams. High-level functions that operate on streams, including formatted input and output. Discussion of the lecture evaluation. Discussion of project part I.

3 The Standard I/O Library 3 Input and output functionality of the ISO C standard library Specified by the ISO C standard. Has been implemented on many OSs other than UNIX. Additional interfaces defined as extensions by SUSv3. Handles details such as buffer allocation and performing I/O in optimal-sized chunks (no need to worry about using the correct buffer size). Ease of use. Initially written by Dennis Ritchie around 1975.

4 Streams and FILE Objects 4 Unbuffered I/O File descriptors So far I/O centered around file descriptors. When a file is opened a file descriptor is returned. It was used for all subsequent I/O operations. Standard I/O Library Streams Standard I/O centers around streams. When opening or creating a file we say that we associate a stream with the file (fopen(3) returns a pointer to FILE). FILE contains all the information required by the standard I/O library to manage the stream.

5 The FILE object 5 Typical members of the FILE structure The file descriptor used for actual I/O. A pointer to a buffer for the stream. The size of the buffer. Count of the number of characters currently in the buffer. An error flag. Incidental Remark In general there is no need to examine a FILE object, just pass the pointer as an argument to each standard I/O function. A pointer with type FILE * is referred to as a file pointer.

6 Single- and Multibyte Character Sets 6 Standard I/O file streams can be used with single-byte and multibyte ( wide ) character sets. ASCII character set: A single character is represented by a single byte. International character sets: A character can be represented by more than one byte. A stream s orientation determines whether the characters that are read and written are single-byte or multibyte. Initially, when a stream is created, it has no orientation. If a multibyte I/O function ( wchar.h) is used on a stream without orientation, the stream s orientation is set to wide-oriented, and byte-oriented in case of byte I/O functions.

7 Predefined streams 7 Standard Input, Standard Output, and Standard Error 3 predefined streams are automatically available to a process. They refer to the same files as the file descriptors: STDIN FILENO, STDOUT FILENO, and STDERR FILENO. They are referenced through the predefined file pointers stdin, stdout, and stderr, defined in <stdio.h>. /* <stdio.h> */ BEGIN_DECLS extern FILE sf []; END_DECLS # define stdin (& sf [0]) # define stdout (& sf [1]) # define stderr (& sf [2])

8 Buffering 8 The standard I/O library provides buffering Goal is to minimize the number of read and write calls. Buffering is tried to be automatically associated to streams. Applications should not worry about it. Different buffering modes can lead to confusions. Three types of buffering provided by the standard I/O library Fully buffered Line buffered Unbuffered

9 Fully (block) buffered I/O 9 The fully buffered I/O provided by the standard I/O library: Actual I/O takes place when the standard I/O buffer is filled. Files residing on disk are normally fully buffered by the library. The buffer is obtained by one of the I/O functions. Usually by calling malloc(3) the first time I/O takes place. The term flush describes the writing of a standard I/O buffer. A buffer can be flushed automatically by the standard I/O routines such as when a buffer fills. Explicitly, by using the function fflush(3).

10 Line buffered I/O 10 Line buffered I/O provided by the standard I/O library: Actual I/O takes place, when a newline character is encountered on input or output. This allows us to output a single character at a time (e.g., with fputc(3)), knowing that actual I/O will take place only when we finish writing each line. Line buffering is typically used on a stream when it refers to a terminal (e.g., standard input and standard output). However, the size of the buffer is fixed, so I/O might take place if the buffer is filled before a newline is seen.

11 Unbuffered I/O 11 Unbuffered I/O provided by the standard I/O library: The standard I/O library does not buffer the characters. When an output stream is unbuffered, information appears on the destination file/terminal as soon as written write(2). Standard error stream is normally unbuffered. Any error messages are displayed as quickly as possible (regardless whether they contain a newline or not).

12 ISO C Buffering Requirements 12 ISO C requires the following buffering characteristics: Standard input and output are fully buffered, if and only if they do not refer to an interactive device. Standard error is never fully buffered. Should standard input and output be unbuffered or line buffered, if they refer to an interactive device? Should standard error be line buffered or unbuffered? System dependent (for instance OpenBSD) If stdin and stdout refer to a terminal they are line buffered. Standard error is initially unbuffered.

13 Turn Buffering On and Off 13 # include <stdio.h> void setbuf ( FILE * stream, char * buf ); setbuf turns buffering on or off. It may be implemented similar to: /* / usr / src / lib / libc / stdio / setbuf.c */ # include <stdio.h> void setbuf ( FILE *fp, char * buf ) { ( void ) setvbuf ( fp, buf, buf? _IOFBF : _IONBF, BUFSIZ ); }

14 # include <stdio.h> Alter Buffering Behaviour 14 int /* 0 if OK else EOF ( but stream is still functional ) */ setvbuf ( FILE * stream, char * buf, int mode, size_t size ); setvbuf is used to alter the buffering behavior of a stream. May only be used after sucessful open and before first I/O. mode must be one of the following three macros: # define _IOFBF 0 /* setvbuf should set fully buffered */ # define _IOLBF 1 /* setvbuf should set line buffered */ # define _IONBF 2 /* setvbuf should set unbuffered */ For an unbuffered stream, buf and size are ignored. For line or fully buffered streams buf and size can optionally specify a buffer and its size. If buf is NULL the system chooses an apt size 1. 1 System-dependent: BUFSIZE (stdio.h), st blksize (stat.h)

15 Buffer Options and Flushing a Stream 15 The setbuf and setvbuf functions and their options: Function mode buf Buffer & length Type of buffering setbuf setvbuf nonnull user buf of length BUFSIZ fully buffered or line buffered NULL (no buffer) unbuffered IOFBF nonnull user buf of length size NULL system buffer of apt length fully buffered IOLBF nonnull user buf of length size NULL system buffer of apt length line buffered IONBF (ignored) (no buffer) unbuffered At any time, a stream can be flushed: # include <stdio.h> int /* 0 if OK, EOF on failure and errno set */ fflush ( FILE * stream ); Any unwritten data for the stream is passed to the kernel. If stream is NULL, all output streams are flushed.

16 # include <stdio.h> Opening a Stream 16 FILE * fopen ( const char * path, const char * mode ); FILE * freopen ( const char * path, const char * mode, FILE * stream ); FILE * /* all : fpointer if OK, NULL on failure with errno */ fdopen ( int fildes, const char * mode ); fopen opens a specified file freopen opens a specified file on a specified stream. The original stream (if it exists) is always closed. Change the file associated with stderr, stdin, stdout. fdopen is part of Posix.1 not ISO C, as standard I/O does not deal with file descriptors.

17 Modes to Open a Standard I/O Stream 17 ISO C specifies 15 values for opening a standard I/O stream: mode Description r or rb open for reading w or wb truncate to 0 length or create for writing a or ab append; open for writing at end of file, or create for writing r+ or r+b or rb+ open for reading and writing w+ or w+b or wb+ truncate to 0 length or create for reading and writing a+ or a+b or ab+ open or create for reading and writing at end of file Using b allows to differentiate between text and binary files. UNIX kernels do not differentiate between these types of files it has no effect. With fdopen, the meaning of mode differs slightly.

18 Meanings of Open Modes with fdopen 18 fdopen associates a stream with an existing file descriptor Opening for write does not truncate the file. Example: Descriptor was created by open(2). The file already existed. O TRUNC flag is in control whether file is to be truncated. fdopen can not simply truncate any file it opens for writing. Opening for append can not create the file. The file has to exist if a descriptor refers to it.

19 Appending to a Stream 19 Append mode guarantees atomic operation Opening for append: Each write is at the current end of file. If multiple processes open the same file using append mode 2, data from each process will be correctly written to the file. Older versions of UNIX didn t support the append mode, so programs were coded as follows: if ( lseek (fd, 0L, 2) < 0) /* position to EOF... */ err ( errno, " lseek error "); if ( write (fd, buf, 100)!= 100) /*... and write */ err ( errno, " write error "); This works fine for a single process, but problems arise if multiple processes use this technique to append to the same file appending messages to a logfile, for instance. 2 Same holds for O APPEND with open(2) function.

20 Sharing a Single File 20 Figure: Two processes with the same file open [Apue, Fig. 3.7]

21 Lost Update on Append 21 Assume processes A and B append to the same file. 3 Each process has its own file table entry, but they share a single v-node table entry (see Figure 3.7). A performs lseek to EOF and sets current file offset to Kernel switches and schedules B to run. B performs lseek to 1500 (EOF). B performs write and increments current file offset to Since the file size has been extended, the kernel also updates the current file size in the v-node to Kernel switches and A resumes. When A calls write, the data is written at current file offset for A, which is Data wrote by process B is overwritten. Lost update. 3 Without using append mode.

22 Atomic Operation with Append Mode 22 Problem: Logical operation position to EOF and write causes two seperate function calls. Solution: Positioning to the current end of file and the write has to be an atomic operation with regard to other processes. Any operation that requires more than one function call cannot be atomic (kernel can suspend the process in-between). Append mode is an atomic way. Each time a write is performed for a file with this append flag set, the current file offset in the file table entry is first set to the current file size from the i-node table entry. Each every write appends to the (updated) current end of file.

23 Final Remarks on Opening a Stream 23 Six different ways to open a standard I/O stream: Restriction r w a r+ w+ a+ file must already exist x x previous contents of file discarded x x stream can be read x x x x stream can be written x x x x x stream can be written only at end x x Creating a new file with mode w or a, there is no way to specify file s access permission bits, as with open(2). Any created files will have mode S IRUSR S IWUSR S IRGRP S IWGRP S IROTH S IWOTH (0666). With a file opened for reading and writing (+ sign in mode) reads and writes cannot be arbitrarily intermixed. Output shall not be directly followed by input without an intervening fflush. Input shall not be followed by output without repositioning.

24 Closing a stream with fclose(3) 24 # include <stdio.h> int /* 0 if OK, else EOF / errno ( no further access ) */ fclose ( FILE * stream ); An open stream is closed by calling fclose. Any buffered output data is flushed before the file is closed. Any buffered input data is discarded. Any automatically allocated buffers are released. When a process terminates normally (calling exit or returning from main), all open standard I/O streams are closed.

25 Reading and Writing a Stream 25 Once opened a stream there are three different types of I/O: Character-at-a-time I/O. Read and write one character at a time, with the standard I/O functions handling all the buffering (if the stream is buffered). Line-at-a-time I/O. To read or write a line at a time, we use fgets(3) and fputs(3). Each line is terminated with a newline character, and we have to specify the maximum line length we can handle. Direct I/O 4. Provided by fread(3) and fwrite(3). For each operation we read or write some number of objects, where each object is of specified size. These types of I/O are refered to as unformatted I/O. Formatted I/O is done by functions, such as printf or scanf. 4 aka binary I/O, object-at-a-time I/O, record/structure-oriented I/O

26 Character-at-a-time Input Functions 26 # include <stdio.h> int fgetc ( FILE * stream ); int getc ( FILE * stream ); int /* equivalent to getc () with the argument stdin. */ getchar ( void ); Return the next requested object from the stream. Next character as an unsigned char converted to int. The input functions return the same value whether an error occurs or EOF (feof and ferror are used to distinguish).

27 Check Stream Status 27 # include <stdio.h> int /* non - zero if it is set */ feof ( FILE * stream ); int /* non - zero if it is set */ ferror ( FILE * stream ); int clearerr ( FILE * stream ); Most implementations have two flags for each stream in FILE. An error flag. An end-of-file flag. Both flags are cleared by clearerr.

28 # include <stdio.h> Push-Back Characters 28 int /* c if OK, EOF on failure */ ungetc ( int c, FILE * stream ); Characters pushed back return by subsequent reads on the stream in reverse order of their pushing (FILO). One character of push-back is guaranteed, but as long as there is sufficient memory, an effectively infinite amount of pushback is allowed. If a character is successfully pushed-back, the end-of-file indicator for the stream is cleared. Pushing back EOF will fail and the stream remains unchanged. Pushed characters don t get written back to file or device. They are kept incore.

29 Character-at-a-time Output Functions 29 # include <stdio.h> int fputc ( int c, FILE * stream ); int putc ( int c, FILE * stream ); int /* All : c if OK, EOF / errno on failure */ putchar ( int c); The functions write the character c (converted to an unsigned char) to the output stream. EOF is returned if a write error occures, or if an attempt is made to write a read-only stream.

30 # include <stdio.h> Line-at-a-time Input Functions 30 char * fgets ( char * str, int size, FILE * stream ); char * /* should NEVER be used - > unknown buffer size */ gets ( char * str ); /* Both return str if OK, NULL on EOF or error */ str specifies the address of the buffer to read the line into. gets reads from stdin and fgets from stream. With fgets the size of the buffer is specified. The buffer is always null-terminated, i.e., at most size 1 is read. If the line is longer, a partial line is returned. The next call will read what follows.

31 Line-at-a-time Output Functions 31 # include <stdio.h> int /* 0 on success and EOF on error */ fputs ( const char * str, FILE * stream ); int puts ( const char * str ); /* >=0 on success and EOF or error */ fputs writes the string pointed to by str to the stream pointed to by stream. puts writes the string str, and a terminating newline character, to the stream stdout.

32 Binary I/O 32 Motivation for binary I/O Read or write an entire structure at a time. With character-at-a-time functions, such as getc or putc we have to loop through an entire structure. Line-at-a-time functions will not work. fputs stops writing when it hits a null byte. fgets won t work right on input with null or newline bytes.

33 # include <stdio.h> Binary I/O Functions 33 size_t fread ( void * ptr, size_t size, size_t nmemb, FILE * stream ); size_t fwrite ( const void * ptr, size_t size, size_t nmemb, FILE * stream ); /* Return number of objects read or written */ fread reads nmemb objects, each size bytes long. Input is taken from stream and stored at the location ptr. Both return number of objects read or written. For read it can be less than nmemb if error occurs or EOF. 5 For write an error has occured if it is not equal to nmemb. 5 ferror and feof must be called to determine.

34 Binary I/O Write an Array 34 The functions have two common cases: Read or write a binary array float data [10]; if ( fwrite (& data [2], sizeof ( float ), 4, fp)!= 4) err (1, " fwrite error."); size as the size of each element of the array. nmemb as the number of elements.

35 Binary I/O Write a Structure 35 Read or write a structure struct tuple { unsigned int size ; unsigned int level ; enum kind kind ; void * cnt ; } tup ; if ( fwrite (& tup, sizeof ( tup ), 1, fp)!= 1) err (1, " fwrite error."); size as the size of structure. nmemb as one (the number of objects to write).

36 Fundamental Problems with Binary I/O 36 Binary formats change between compilers and architectures Binary formats used to store multibyte integers and floating-point values differ among machine architectures. The offset of a member within a structure can differ between compilers and systems. Even on a single system, the binary layout of a structure can differ, depending on compiler options. To exchanging binary data among different systems a higher-level protocol is probably the better choice.

37 Positioning a Stream 37 There are three ways to position a standard I/O stream: ftell and fseek. File position stored as long. (Historic) ftello and fseeko. File position stored as off t. (SUSv3) fgetpos and fsetpos. File position stored as fpos t. (ISO C) They work similar to lseek(2) and the whence options (SEEK SET etc.) are the same.

38 Obtaining a File Descriptor 38 # include <stdio.h> int /* file descriptor assoc. with the stream */ fileno ( FILE * stream ); On UNIX, the standard I/O library ends up calling the low-level I/O routines. Each standard I/O stream has an associated file descriptor. fileno can obtain the descriptor (SUSv3, not ISO C).

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

Standard I/O in C, Computer System and programming in C Standard I/O in C, Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information 7. Environment

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized

More information

1. Systems Programming using C (File Subsystem)

1. Systems Programming using C (File Subsystem) 1. Systems Programming using C (File Subsystem) 46 Intended Schedule Date Lecture Hand out Submission 0 20.04. Introduction to Operating Systems Course registration 1 27.04. Systems Programming using C

More information

1. Systems Programming using C (File Subsystem)

1. Systems Programming using C (File Subsystem) Intended Schedule 1. Systems Programming using C (File Subsystem) Date Lecture Hand out Submission 0 20.04. Introduction to Operating Systems Course registration 1 27.04. Systems Programming using C (File

More information

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

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

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

File (1A) Young Won Lim 11/25/16 File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or

More information

CSE 410: Systems Programming

CSE 410: Systems Programming CSE 410: Systems Programming Input and Output Ethan Blanton Department of Computer Science and Engineering University at Buffalo I/O Kernel Services We have seen some text I/O using the C Standard Library.

More information

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

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System What Is Operating System? Operating Systems, System Calls, and Buffered I/O emacs gcc Browser DVD Player Operating System CS 217 1 Abstraction of hardware Virtualization Protection and security 2 Academic

More information

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection 1 Files 1.1 File functions Opening Files : The function fopen opens a file and returns a FILE pointer. FILE *fopen( const char * filename, const char * mode ); The allowed modes for fopen are as follows

More information

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

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. 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

More information

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

UNIT IV-2. The I/O library functions can be classified into two broad categories: UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known

More information

C Basics And Concepts Input And Output

C Basics And Concepts Input And Output C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus

More information

Naked C Lecture 6. File Operations and System Calls

Naked C Lecture 6. File Operations and System Calls Naked C Lecture 6 File Operations and System Calls 20 August 2012 Libc and Linking Libc is the standard C library Provides most of the basic functionality that we've been using String functions, fork,

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

File System User API

File System User API File System User API Blunk Microsystems file system API includes the file-related routines from Standard C and POSIX, as well as a number of non-standard functions that either meet a need unique to embedded

More information

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

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by

More information

Goals of this Lecture

Goals of this Lecture I/O Management 1 Goals of this Lecture Help you to learn about: The Unix stream concept Standard C I/O functions Unix system-level functions for I/O How the standard C I/O functions use the Unix system-level

More information

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture! I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture! I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix

More information

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

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

File I/O. Preprocessor Macros

File I/O. Preprocessor Macros Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically

More information

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e Storage of data in variables and arrays is temporary such data is lost when a program terminates. Files are used for permanent retention of data. Computers store files on secondary

More information

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

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch. 1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions

More information

ENG120. Misc. Topics

ENG120. Misc. Topics ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 15: Unix interface: low-level interface Cristina Nita-Rotaru Lecture 15/Fall 2013 1 Streams Recap Higher-level interface, layered on top of the primitive file descriptor

More information

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

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper. File IO part 2 Files Programs and data are stored on disk in structures called files Examples a.out binary file lab1.c - text file term-paper.doc - binary file Overview File Pointer (FILE *) Standard:

More information

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

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based Chapter 5, Standard I/O Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based #include FILE *f; Standard files (FILE *varname) variable: stdin File Number: STDIN_FILENO

More information

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

System Programming. Standard Input/Output Library (Cont d) Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Binary I/O 2 3 4 5 Binary

More information

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

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15 Day14 A Young W. Lim 2017-12-26 Tue Young W. Lim Day14 A 2017-12-26 Tue 1 / 15 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-12-26 Tue 2 / 15 Based

More information

C-Refresher: Session 10 Disk IO

C-Refresher: Session 10 Disk IO C-Refresher: Session 10 Disk IO Arif Butt Summer 2017 I am Thankful to my student Muhammad Zubair bcsf14m029@pucit.edu.pk for preparation of these slides in accordance with my video lectures at http://www.arifbutt.me/category/c-behind-the-curtain/

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

UNIX System Programming

UNIX System Programming File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,

More information

C File Processing: One-Page Summary

C File Processing: One-Page Summary Chapter 11 C File Processing C File Processing: One-Page Summary #include int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be

More information

#define PERLIO_NOT_STDIO 0 /* For co-existence with stdio only */ #include <perlio.h> /* Usually via #include <perl.h> */

#define PERLIO_NOT_STDIO 0 /* For co-existence with stdio only */ #include <perlio.h> /* Usually via #include <perl.h> */ NAME SYNOPSIS perlapio - perl's IO abstraction erface. #define PERLIO_NOT_STDIO 0 /* For co-existence with stdio only */ #include /* Usually via #include */ PerlIO *PerlIO_stdin();

More information

File IO and command line input CSE 2451

File IO and command line input CSE 2451 File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to

More information

System Software Experiment 1 Lecture 7

System Software Experiment 1 Lecture 7 System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018

More information

HIGH LEVEL FILE PROCESSING

HIGH LEVEL FILE PROCESSING HIGH LEVEL FILE PROCESSING 1. Overview The learning objectives of this lab session are: To understand the functions used for file processing at a higher level. o These functions use special structures

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

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

File Access. FILE * fopen(const char *name, const char * mode); File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header

More information

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

Chapter 12. Files (reference: Deitel s chap 11) chap8 Chapter 12 Files (reference: Deitel s chap 11) 20061025 chap8 Introduction of File Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

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

CSI 402 Lecture 2 Working with Files (Text and Binary) CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value

More information

Computer programming

Computer programming Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci T.U. Cluj-Napoca - Computer

More information

UNIX input and output

UNIX input and output UNIX input and output Disk files In UNIX a disk file is a finite sequence of bytes, usually stored on some nonvolatile medium. Disk files have names, which are called paths. We won t discuss file naming

More information

Chapter 11 File Processing

Chapter 11 File Processing 1 Chapter 11 File Processing Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3

More information

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14 Day14 A Young W. Lim 2017-11-02 Thr Young W. Lim Day14 A 2017-11-02 Thr 1 / 14 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-11-02 Thr 2 / 14 Based

More information

Computer Programming Unit v

Computer Programming Unit v READING AND WRITING CHARACTERS We can read and write a character on screen using printf() and scanf() function but this is not applicable in all situations. In C programming language some function are

More information

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output Basic I/O COSC2031 - Software Tools C - Input/Output (K+R Ch. 7) We know how to do some basic input and output: getchar - reading characters putchar - writing characters printf - formatted output Input

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight Exercise 7 due Monday (out later today) POSIX Portable Operating System Interface Family of standards specified by the

More information

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

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan File Processing Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential

More information

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12 BIL 104E Introduction to Scientific and Engineering Computing Lecture 12 Files v.s. Streams In C, a file can refer to a disk file, a terminal, a printer, or a tape drive. In other words, a file represents

More information

Ch 11. C File Processing (review)

Ch 11. C File Processing (review) Ch 11 C File Processing (review) OBJECTIVES To create, read, write and update files. Sequential access file processing. Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits

More information

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

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline. CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random

More information

2009 S2 COMP File Operations

2009 S2 COMP File Operations 2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations

More information

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)

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) 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) No C language primitives for I/O; all done via function

More information

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc. Compound Statements So far, we ve mentioned statements or expressions, often we want to perform several in an selection or repetition. In those cases we group statements with braces: i.e. statement; statement;

More information

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

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 8 Data Files Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To be able to create, read, write and update

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

Fundamentals of Programming. Lecture 15: C File Processing

Fundamentals of Programming. Lecture 15: C File Processing 1 Fundamentals of Programming Lecture 15: C File Processing Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this course

More information

File and Console I/O. CS449 Spring 2016

File and Console I/O. CS449 Spring 2016 File and Console I/O CS449 Spring 2016 What is a Unix(or Linux) File? File: a resource for storing information [sic] based on some kind of durable storage (Wikipedia) Wider sense: In Unix, everything is

More information

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

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions. UNIT-V Unit-5 File Streams Formatted I/O Preprocessor Directives Printf Scanf A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

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

fopen() fclose() fgetc() fputc() fread() fwrite() The ability to read data from and write data to files is the primary means of storing persistent data, data that does not disappear when your program stops running. The abstraction of files that C provides

More information

CAAM 420 Notes Chapter 2: The C Programming Language

CAAM 420 Notes Chapter 2: The C Programming Language CAAM 420 Notes Chapter 2: The C Programming Language W. Symes and T. Warburton October 2, 2013 22 Stack Overflow Just for warmup, here is a remarkable memory bust: 1 / Author : WWS 3 Purpose : i l l u

More information

CE Lecture 11

CE Lecture 11 Izmir Institute of Technology CE - 104 Lecture 11 References: - C: A software Engineering Approach 1 In this course you will learn Input and Output Sorting Values 2 Input and Output Opening and Closing

More information

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

Computer Programming: Skills & Concepts (CP) Files in C CP 20 slide 1 Tuesday 21 November 2017 Computer Programming: Skills & Concepts (CP) Files in C Julian Bradfield Tuesday 21 November 2017 Today s lecture Character oriented I/O (revision) Files and streams

More information

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

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof() Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who

More information

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Fundamentals of Programming. Lecture 10 Hamed Rasifard Fundamentals of Programming Lecture 10 Hamed Rasifard 1 Outline File Input/Output 2 Streams and Files The C I/O system supplies a consistent interface to the programmer independent of the actual device

More information

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

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

More information

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

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060 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

More information

Data File and File Handling

Data File and File Handling Types of Disk Files Data File and File Handling Text streams are associated with text-mode files. Text-mode files consist of a sequence of lines. Each line contains zero or more characters and ends with

More information

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

CS 261 Fall Mike Lam, Professor. Structs and I/O CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful

More information

Lecture 9: File Processing. Quazi Rahman

Lecture 9: File Processing. Quazi Rahman 60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,

More information

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

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who

More information

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University File I/O Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Unix Files A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Lecture 8: Structs & File I/O

Lecture 8: Structs & File I/O ....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \

More information

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

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

Programming in C Lecture Tiina Niklander

Programming in C Lecture Tiina Niklander Programming in C Lecture 4 24.9.2018 Tiina Niklander 2018 1 Week 3 exercises Week 3 exercises cover Files Open, close Different read functions Update Moving the read/write position counter Doubly linked

More information

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

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing Chapter 14: File Processing Files and Streams C views each file simply as a sequential stream of bytes. It ends as if there is an end-of-file marker. The data structure FILE, defined in stdio.h, stores

More information

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

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C Outline Review HW1 (+command line arguments) Memory Layout File I/O HW1 REVIEW HW1 Common Problems Taking input from stdin (via scanf) Performing

More information

Lecture6 File Processing

Lecture6 File Processing 1 Lecture6 File Processing Dr. Serdar ÇELEBİ 2 Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a Sequential Access File Updating Sequential Access

More information

EM108 Software Development for Engineers

EM108 Software Development for Engineers EE108 Section 4 Files page 1 of 14 EM108 Software Development for Engineers Section 4 - Files 1) Introduction 2) Operations with Files 3) Opening Files 4) Input/Output Operations 5) Other Operations 6)

More information

Input/Output and the Operating Systems

Input/Output and the Operating Systems Input/Output and the Operating Systems Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 I/O Functions Formatted I/O printf( ) and scanf( ) fprintf( ) and fscanf( ) sprintf( ) and sscanf( ) int printf(const char*

More information

Input/Output Systems Prof. James L. Frankel Harvard University

Input/Output Systems Prof. James L. Frankel Harvard University Input/Output Systems Prof. James L. Frankel Harvard University Version of 5:20 PM 28-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved. I/O Overview Different kinds of devices Mass storage

More information

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

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA 7/21/2014 1 FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA What s a file? A named section of storage, usually on a disk In C, a file is a continuous sequence of bytes Examples for the demand of a

More information

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

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre Programming in C Session 8 Seema Sirpal Delhi University Computer Centre File I/O & Command Line Arguments An important part of any program is the ability to communicate with the world external to it.

More information

File I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

File I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University  Embedded Software Lab. 1 File I/O Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Unix files 2 A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices are represented

More information

File and Console I/O. CS449 Fall 2017

File and Console I/O. CS449 Fall 2017 File and Console I/O CS449 Fall 2017 What is a Unix(or Linux) File? Narrow sense: a resource provided by OS for storing informalon based on some kind of durable storage (e.g. HDD, SSD, DVD, ) Wide (UNIX)

More information

Process Management! Goals of this Lecture!

Process Management! Goals of this Lecture! Process Management! 1 Goals of this Lecture! Help you learn about:" Creating new processes" Programmatically redirecting stdin, stdout, and stderr" Unix system-level functions for I/O" The Unix stream

More information

Library Functions. General Questions

Library Functions. General Questions 1 Library Functions General Questions 1. What will the function rewind() do? A. Reposition the file pointer to a character reverse. B. Reposition the file pointer stream to end of file. C. Reposition the

More information

1 The CTIE processor INTRODUCTION 1

1 The CTIE processor INTRODUCTION 1 1 The CTIE processor INTRODUCTION 1 1. Introduction. Whenever a programmer wants to change a given WEB or CWEB program (referred to as a WEB program throughout this program) because of system dependencies,

More information

M.CS201 Programming language

M.CS201 Programming language Power Engineering School M.CS201 Programming language Lecture 16 Lecturer: Prof. Dr. T.Uranchimeg Agenda Opening a File Errors with open files Writing and Reading File Data Formatted File Input Direct

More information

File I/O - Filesystems from a user s perspective

File I/O - Filesystems from a user s perspective File I/O - Filesystems from a user s perspective Unix Filesystems Seminar Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz

More information

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

CMPS 105 Systems Programming. Prof. Darrell Long E2.371 + CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 3: File I/O 2 + File I/O 3 n What attributes do files need? n Data storage n Byte stream n Named n Non-volatile n Shared

More information

Lecture 3. Introduction to Unix Systems Programming: Unix File I/O System Calls

Lecture 3. Introduction to Unix Systems Programming: Unix File I/O System Calls Lecture 3 Introduction to Unix Systems Programming: Unix File I/O System Calls 1 Unix File I/O 2 Unix System Calls System calls are low level functions the operating system makes available to applications

More information

C PROGRAMMING Lecture 6. 1st semester

C PROGRAMMING Lecture 6. 1st semester C PROGRAMMING Lecture 6 1st semester 2017-2018 Input/Output Most programs require interaction (input or output. I/O is not directly supported by C. I/O is handled using standard library functions defined

More information