UNIX input and output

Similar documents
Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

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

CSE 410: Systems Programming

Inter-Process Communication

Goals of this Lecture

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

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

Layers in a UNIX System. Create a new process. Processes in UNIX. fildescriptors streams pipe(2) labinstructions

CSE 333 SECTION 3. POSIX I/O Functions

Process Creation in UNIX

CMPSC 311- Introduction to Systems Programming Module: Input/Output

Input / Output Functions

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

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

Summer June 15, 2010

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Systems Programming. COSC Software Tools. Systems Programming. High-Level vs. Low-Level. High-Level vs. Low-Level.

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

Lecture 8: Structs & File I/O

Binghamton University. CS-220 Spring Includes & Streams

Data and File Structures Chapter 2. Basic File Processing Operations

CSE 333 SECTION 3. POSIX I/O Functions

UNIX I/O. Computer Systems: A Programmer's Perspective, Randal E. Bryant and David R. O'Hallaron Prentice Hall, 3 rd edition, 2016, Chapter 10

OS COMPONENTS OVERVIEW OF UNIX FILE I/O. CS124 Operating Systems Fall , Lecture 2

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

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

CS240: Programming in C

Lecture 7: file I/O, more Unix

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

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

Standard File Pointers

File IO and command line input CSE 2451

CS240: Programming in C

Process Management! Goals of this Lecture!

C Basics And Concepts Input And Output

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Processes COMPSCI 386

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

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

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

Standard C Library Functions

Input and Output System Calls

CS 201. Files and I/O. Gerson Robboy Portland State University

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

All the scoring jobs will be done by script

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

Outline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra

The link() System Call. Preview. The link() System Call. The link() System Call. The unlink() System Call 9/25/2017

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

PROGRAMMAZIONE I A.A. 2017/2018

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

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

UNIX System Programming

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

File I/O and File Systems

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

CSC209 Review. Yeah! We made it!

ENG120. Misc. Topics

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

System Software Experiment 1 Lecture 7

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)

Section 3: File I/O, JSON, Generics. Meghan Cowan

CSC 271 Software I: Utilities and Internals

Input/Output: Advanced Concepts

Advanced C Programming Topics

PEMP ESD2531. I/O and File System. Session Speaker. Deepak V. M.S Ramaiah School of Advanced Studies - Bengaluru

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu

2009 S2 COMP File Operations

Computer Programming Unit v

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Contents. A Review of C language. Visual C Visual C++ 6.0

Operating System Labs. Yuanbin Wu

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

Contents. Programming Assignment 0 review & NOTICE. File IO & File IO exercise. What will be next project?

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

Motivation. Operating Systems. File Systems. Outline. Files: The User s Point of View. File System Concepts. Solution? Files!

All the scoring jobs will be done by script

211: Computer Architecture Summer 2016

Intermediate Programming, Spring 2017*

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Sistemas Operativos /2016 Support Document N o 1. Files, Pipes, FIFOs, I/O Redirection, and Unix Sockets

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING SOFTWARE ENGINEERING DEPARTMENT

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

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

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

File I/O. Preprocessor Macros

structs as arguments

The course that gives CMU its Zip! I/O Nov 15, 2001

CMSC 216 Introduction to Computer Systems Lecture 17 Process Control and System-Level I/O

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

Lecture 03 Bits, Bytes and Data Types

25.2 Opening and Closing a File

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Lecture 23: System-Level I/O

Contents. NOTICE & Programming Assignment 0 review. What will be next project? File IO & File IO exercise

Computer Architecture and Assembly Language. Practical Session 5

Transcription:

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 or permissions here Opening a file In UNIX, files must be opened before being read and closed after. Here is a function call to open a disk file named /Users/alice/adventures.txt for reading. int fd = open("/users/alice/adventures.txt", O_RDONLY); Notice that open returns an integer. If the integer is negative, the file could not be opened. If the integer is not negative, it is a file descriptor. A file descriptor is an index into a table called the descriptor table. Each process has its own descriptor table, so the file descriptor only has meaning within the context of a given process. Reading a file Once a file is open, the process uses the file descriptor to refer to the open file. Typeset June 11, 2016 1

For example, to read up to 10 bytes from the file, I can use unsigned char buffer[10]; int count = read( fd, buffer, 10 ); The call to read will return -1 if there was an error 0 if we have reached the end of the file a positive number giving the number of bytes successfully read Here is a complete program that reads a file and prints its contents in hexadecimal. Typeset June 11, 2016 2

Notes: On line 16, the file is opened, returning a file descriptor. On line 19, I allocated space to hold the data read On line 22, up to 1024 bytes are read from the file into array buffer. The number of characters read is saved in variable count. On line 24, I checked for the end of the file. One lines 25 28, each character read by the previous read, is output. On line 25 the value of count is between 1 and 1024 Typeset June 11, 2016 3

inclusive. Writing files Writing files is similar to reading. The following function call will open a file "out.txt" for reading or writing const int flags = O_WRONLY O_CREAT O_TRUNC; const int mode = S_IRUSR S_IWUSR; int outfd = open( argv[2], flags, mode ); The flags indicate that The process will only write to the file The file should be created if it does not already exist The file s length should be truncated to 0 if it already exists. The mode indicates that if a new file is created then: The owner of the file should be allowed to read it. The owner of the file should be allowed to write to it. As before the open method returns a file descriptor or an error indicator. We can write to a file using the file descriptor. unsigned char buffer[ 10 ]; /* Put up to10 bytes of data into buffer. */ int writecount = write( outfd, buffer, 10 ); This call will write up to 10 bytes to the file. The result is either Less than 0, indicating an error. Typeset June 11, 2016 4

Greater or equal to 0, indicating how many bytes were written. Here is a program that simply copies the contents of a file to a new file. Notes on the program On line 19, I open a file for writing. Lines 27 to 32, repeatedly call write until all data in the buffer is written. Lines 29 to 30 deal with errors that we can recover from by trying again. Typeset June 11, 2016 5

The loop on lines 27 32 is not strictly needed. We could replace it with int writecount = write( outfd, buffer, count ); check( writecount>= 0, "Error on write" ); because for disk files, it is always the case that there is an error or all bytes are written. However, as we will see later, we can also use write to write to sockets and pipes, and in those cases the write may only write some data. So using a loop to write is the preferred method. Closing files We can close a file when we no longer need to read or write to it. int err = close( filedescriptor ); After a file is closed its descriptor can not be used until the descriptor is recycled later. Files are also closed when the process terminates; so I didn t put close in my programs. The wonderful thing about file descriptors In UNIX we can open things that aren t disk files. For example devices. A device might be the keyboard, a mouse, a printer, a terminal, a disk drive, a memory card. We can use the read and write system calls to read from and write data to devices. Standard input, standard output, and Typeset June 11, 2016 6

standard error By convention whenever a Unix program is started, it will have 3 files open with descriptors 0, 1, 2 0 represents the standard input stream 1 represents the standard output stream 2 represents the standard error stream If you start a UNIX program from shell in a terminal window, then 0, 1, and 2 represent that window. Running the hellounix program (see below) on a OS X terminal window, we get: This works because the program writes to file descriptor 1 and file descriptor 1 represents the Terminal window. There is no need for the program to open the terminal for writing because the UNIX shell arranges that when the hellounix program starts, file descriptor 1 (and 0 and 2) represent the terminal. File descriptors 0, 1, and 2 can be bound to actual disk files, if you like. Typeset June 11, 2016 7

This time the shell created a file called out.txt and bound it to file descriptor 1 before starting the program. UNIX pipes work a similar way. The UNIX shell command fred ginger starts processes running programs fred and ginger at the same time. Before starting them: It creates a pipe, which is a sort of a queue of bytes. It arranges that in the fred process, 1 represents the pipe. It arranges that in the ginger process, 0 represents the pipe. Thus the standard output of the first process is the standard input of the second. Object oriented I/O So file descriptors can represent Disk files. Devices such as printers, keyboards, and entire disks. Virtual devices such as terminal windows, and pipes. Typeset June 11, 2016 8

A program (or subroutine) can work with any of these objects without the programmer having to worry about what sort of object it is. The programmer just uses read and write and assumes the object will interpret the call reasonably. See the RIO functions in the text book, for example. They will work with any appropriate object. They are polymorphic functions. Soon we will look at how we can use this idea to perform input and output across the internet. The C way of I/O vs, the UNIX way of I/O [Not to be covered in class. Please read anyway. It s good stuff to know] Standard C functions You may be wondering about how write relates to C s printf function and to C++ s cout object. Operating systems and languages both define interfaces, but they are not the same interfaces. open, read, write, and close are defined in the UNIX standard. They may not be available or have the same meaning in other operating systems (for example Windows). Of course C and C++ are intended to be portable across many operating systems. So the C language standard defines its own, but different, library functions, such as fopen, getc, putc, fclose. C also Typeset June 11, 2016 9

has functions that build on top of these functions such as fwrite, fread, fprintf, fscanf, printf, and scanf. If a C program is running on UNIX, all these functions ultimately use UNIX functions like open, read, write, and close. But if a C program is running on Windows, these function use Windows system calls. Similarly C++ defines portable input/output objects such as cin, cout, cerr on top of the C functions. Don t mix UNIX and standard C functions on the same input or output stream. FILE objects and FILE* pointers. In place of file descriptors, C uses objects of type FILE. For example the C function fopen creates a FILE object and returns a pointer to that object. The C function putc takes a pointer to a FILE object and a character and outputs the character. Before the main function is called, 3 FILE objects created and three pointers to them are initialized. stdin stdout stderr So if a C program runs on UNIX, we have a choice. We could write Typeset June 11, 2016 10

Or we could be more portable and write The C printf(... ) function is the same as fprintf( stdout,... ) For more on the C functions see http://www.cplusplus.com/reference/cstdio/ Typeset June 11, 2016 11