File and Console I/O. CS449 Fall 2017

Similar documents
File and Console I/O. CS449 Spring 2016

CS240: Programming in C

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

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

File I/O. Preprocessor Macros

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

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

25.2 Opening and Closing a File

UNIX System Programming

Standard File Pointers

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Input/Output and the Operating Systems

PROGRAMMAZIONE I A.A. 2017/2018

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

File IO and command line input CSE 2451

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

Naked C Lecture 6. File Operations and System Calls

Operating System Labs. Yuanbin Wu

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

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

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

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

C-Refresher: Session 10 Disk IO

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

CS240: Programming in C

CSE 410: Systems Programming

System Software Experiment 1 Lecture 7

2009 S2 COMP File Operations

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

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

EM108 Software Development for Engineers

Goals of this Lecture

[6 marks] All parts of this question assume the following C statement. Parts (b) through (e) assume a variable called ptrs.

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

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

Data File and File Handling

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

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

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

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

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

System Calls & Signals. CS449 Spring 2016

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

CP2 Revision. theme: file access and unix programs

File Handling. Reference:

Operating System Labs. Yuanbin Wu

structs as arguments

HIGH LEVEL FILE PROCESSING

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

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

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

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

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

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

Student Number: Instructor: Reid Section: L0201 (12:10-1:00pm)

Jacobs University Bremen February 7 th, 2017 Dr. Kinga Lipskoch. Practice Sheet. First Name:... Last Name:... Matriculation Number:...

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

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

File Descriptors and Piping

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

Fundamentals of Programming. Lecture 10 Hamed Rasifard

C File Processing: One-Page Summary

C Basics And Concepts Input And Output

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

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

Input / Output Functions

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Intermediate Programming, Spring 2017*

Summer June 15, 2010

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

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

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)

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

CSC 209H1 S 2012 Midterm Test Duration 50 minutes Aids allowed: none. Student Number: # 1: / 7

Process Management! Goals of this Lecture!

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

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

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

CSE 333 SECTION 3. POSIX I/O Functions

CSC 209H1 S 2012 Midterm Test Duration 50 minutes Aids allowed: none. Student Number: # 1: / 6

Lecture 9: File Processing. Quazi Rahman

Stream Model of I/O. Basic I/O in C

Computer programming

Introduc)on to I/O. CSE 421/521: Opera)ng Systems Karthik Dantu

UNIX input and output

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

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

C PROGRAMMING Lecture 6. 1st semester

ENG120. Misc. Topics

Standard C Library Functions

Exercise Session 3 Systems Programming and Computer Architecture

Device Drivers. CS449 Fall 2017

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

UNIT- 2. Binary File

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

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

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

Transcription:

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) sense: an interface provided by OS for not only storing but also exchanging info Between programs and the OS Between two programs Interface uses a stream of bytes abstraclon Interfaces are organized as nodes in a file system

What is a Unix(or Linux) File? Examples of files In Unix: Storage resource: TradiLonal files, directories, links OS è Program communicalon interface Devices (keyboards, network cards, printers) Device drivers expose informalon through files Standard localon is under the /dev/ directory Processes (instances of running programs) Info and control of processes is provided through files Standard localon is under the /proc/ directory Program è Program communicalon interface Interprocess communicalon (pipes, shared memory, sockets) Files for IPC can be placed in any agreed upon place

UNIX File Interface A file, in abstract, is a stream of bytes OS Interface consists of five system calls: open(): opens a file and returns a file descriptor File descriptor: index into an OS array called open file table close(): closes file descriptor read(): reads current offset through file descriptor write(): writes current offset through file descriptor lseek(): changes current offset in file Some files do not support certain operalons E.g. a terminal device does not support lseek E.g. a DVD device does not support write

C Standard Library Wrappers C Standard Library wraps file system calls in library funclons 1. For portability across mullple systems 2. To provide more features (buffering, forma_ng) Prin` implements forma_ng on top of write() system call Prin` does line buffering by default when prinlng to screen Buffering controlled using setbuf() calls (remember those?) Works on FILE * instead of file descriptor FILE is a library data structure that abstracts a file FILE data structure contains file descriptor, arrays for internal buffers, flags for buffering mode etc.

Anatomy of UNIX File System Source: M. Tim Jones, Anatomy of the Linux kernel, 06 June 2007 Apps can use either system calls or C library calls to access files Virtual file system implements the 5 system calls for file access Relies on a real file system (ext3, reiser) or pseudo file system (proc, dev) to perform access on devices or OS data structures

Wrappers for the Five System Calls Defined in C Standard library, #include <stdio.h> Func2on Prototype FILE *fopen(const char *path, const char *mode); 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); int fseek(file *stream, long offset, int whence); int fclose(file *fp); Descrip2on Opens the file named by path and associates a stream with it. Returns NULL if error. Reads nmemb elements of data, each size bytes long, from stream, storing them at the localon given by ptr. Writes nmemb elements of data, each size bytes long, to stream, obtaining them from the localon given by ptr. Sets file posilon for stream. The new posilon is offset bytes + posilon specified by whence, which can be one of SEEK_SET, SEEK_CUR, SEEK_END. Flushes the stream pointed to by fp, emptying the buffer, and closes the underlying file descriptor.

Mode r Descrip2on File Open Modes Open text file for reading. Stream is posiloned at the beginning of the file. r+ Same as above, except can write. w Truncate file to zero length or create text file for wrilng. Stream is posiloned at the beginning of the file. w+ Same as above, except can read. a Open for appending or create text file for wrilng. Stream is posiloned at the end of the file. a+ Same as above, except can read. Stream for reading is posiloned at the beginning of the file. Stream for wrilng is posiloned at the end of the file. Adding b to mode string changes file to binary mode, or raw mode - E.g. rb, w+b, wb+ - Disables conversions done in text mode for OS compalbility (E.g. A newline in Unix is \n but in Windows \r\n )

#include <stdio.h> int main() { FILE *rfile; int nread; char buf[100]; Binary File Dump Example >>./a.out #include <stdio.h> int main() char buf[100]; if((rfile=fopen( main.c","rb"))==null) return 1; { FILE *rfile; int nread; while(nread = fread(buf, sizeof(char), 100, if((rfile=fopen( main.c","rb"))==null) rfile)) { return 1; fwrite(buf, sizeof(char), nread, stdout); while(nread = fread(buf, sizeof(char), 100, rfile)) { fwrite(buf, sizeof(char), nread, stdout); fclose(rfile); return 0; fclose(rfile); return 0;

Feof and Ferror Func2on Prototype int feof(file *stream); int ferror(file *stream); void perror(const char *str); Descrip2on Returns non-zero if end-of-file Returns non-zero if error occurred Prints descriplve error message on the last error encountered, prefixed by str: Proper way to do fread(): if(fread(buf, sizeof(char), length, rfile)!= length) { if(feof(rfile)) prin`( End of file.\n ); else if(ferror(rfile)) perror( Error ); else { /* unreachable */ fread() reading less than requested bytes means either end-of-file or error Must use feof and ferror to determine which occurred

AddiLonal (Text) File I/O FuncLons Func2on Prototype int fgetc(file *stream); int fputc(int c, FILE *stream); char *fgets(char *s, int size, FILE *stream); int fputs(const char *s, FILE *stream); int fscanf(file *stream, const char *format,...); int fprin>(file *stream, const char *format,...); Descrip2on Reads the next character from stream and returns it. Returns EOF on end-of-file or error. Writes the character c to stream. Returns c on success or EOF on error. Reads in at most one less than size characters from stream and stores them into buffer s. Reading stops axer an EOF or a newline. A '\0' is stored axer the last character in the buffer. Returns s on success and NULL on error. Writes the string s to stream, without its trailing '\0'. Returns non-negalve number on success, EOF on error. Same as scanf, except reading from stream rather than stdin. Same as prin`, except wrilng to stream rather than stdout.

#include <stdio.h> int main() { FILE *rfile; char buf[100]; Text File Dump Example char buf[100]; if((rfile=fopen("main.c","r"))==null) return 1; while(fgets(buf, 100, rfile)) { fputs(buf, stdout); fclose(rfile); return 0; >>./a.out #include <stdio.h> int main() { FILE *rfile; if((rfile=fopen("main.c","r"))==null) return 1; while(fgets(buf, 100, rfile)) { fputs(buf, stdout); fclose(rfile); return 0;

Standard I/O There are three standard file descriptors for console I/O declared in <stdio.h> extern FILE *stdin; (for standard input) extern FILE *stdout; (for standard output) extern FILE *stderr; (for standard error) stdout is used for normal output; stderr is used to output error messages prin`( ) is equivalent to fprin`(stdout,...) Underlying file descriptors for stdin, stdout, stderr are 0, 1, 2 respeclvely

Standard I/O RedirecLon Unix shells allow standard I/O to be redirected to/from another file Operator command [N]< file command [N]> file Descrip2on Redirect input of file descriptor N to file while running command. N defaults to 0 (stdin). Redirect output of file descriptor N to file while running command. N defaults to 1 (stdout). If file does not exist, it is created. If it exists, it is truncated. command [N]>> file Redirect output of file descriptor N to file while running command. N defaults to 1 (stdout). If file does not exist, it is created. If it exists, output is appended to end of file. Examples: ls -l >./ls.out 2>./ls.err (redirect stdout to ls.out and stderr to ls.err) cat <./ls.out (redirect ls.out to stdin of cat)

File RedirecLon Viewed Through /proc ls -l /proc/self/fd: lists file descriptors for current process (ls) 0, 1, 2 are stdin, stdout, stderr and connected to pts 0 (console) 3 is /proc/16970/fd (a link to directory /proc/self/fd opened by ls) (84) thot $ ls -l /proc/self/fd total 0 lrwx------ 1 wahn UNKNOWN1 64 Sep 11 13:37 0 -> /dev/pts/0 lrwx------ 1 wahn UNKNOWN1 64 Sep 11 13:37 1 -> /dev/pts/0 lrwx------ 1 wahn UNKNOWN1 64 Sep 11 13:37 2 -> /dev/pts/0 lr-x------ 1 wahn UNKNOWN1 64 Sep 11 13:37 3 -> /proc/16970/fd ls -l /proc/self/fd > /tmp/ls.out (redireclng stdout to ls.out) Now 1 (stdout) is changed to /tmp/ls.out (85) thot $ ls -l /proc/self/fd > /tmp/ls.out && cat /tmp/ls.out total 0 lrwx------ 1 wahn UNKNOWN1 64 Sep 11 13:41 0 -> /dev/pts/0 l-wx------ 1 wahn UNKNOWN1 64 Sep 11 13:41 1 -> /tmp/ls.out lrwx------ 1 wahn UNKNOWN1 64 Sep 11 13:41 2 -> /dev/pts/0 lr-x------ 1 wahn UNKNOWN1 64 Sep 11 13:41 3 -> /proc/17025/fd

System Calls Beneath C Library Calls strace./a.out strace is a ullity that prints system calls made by a program a.out is the text file dumper using fgets and fputs run on a source file (116) thoth $ strace./a.out open( hello.c", O_RDONLY) = 3 read(3, "#include <stdio.h>\nint main()\n{\n"..., 4096) = 75 write(1, "#include <stdio.h>\n", 19) = 19 write(1, "int main()\n", 11) = 11 (117) thoth $ strace./a.out >./a.stdout open( hello.c", O_RDONLY) = 3 read(3, "#include <stdio.h>\nint main()\n{\n"..., 4096) = 75 write(1, "#include <stdio.h>\nint main()\n{\n"..., 75) = 75 NoLce the difference in buffering with and w/o stdout redireclon w/o: flushes write buffer on each line (because it is streamed to interaclve terminal) with: flushes buffer only on fclose (for efficiency because it is streamed to storage) UNIX shell calls setbuf() to change buffering policy before launching a.out

File Formats Programmer s responsibility to design file formats Text format (e.g. config files, log files, HTML, XML) + Human readable - Bloated representalon è Numbers are represented as strings - Impossible to do random access (must do sequenlal access) è Usually forma ed using delimiters (e.g. spaces, newlines) Binary format (e.g. image files, database files) + Compact representalon è Numbers are represented in binary + Easy to do random access using lseek è Fixed length records - Needs translalon for human comprehension