Input / Output Functions

Similar documents
Standard File Pointers

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

Standard C Library Functions

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

File IO and command line input CSE 2451

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

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

System Software Experiment 1 Lecture 7

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

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

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

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

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

Course organization. Course introduction ( Week 1)

Input/Output: Advanced Concepts

Input/Output and the Operating Systems

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

C Basics And Concepts Input And Output

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

PROGRAMMAZIONE I A.A. 2017/2018

Advanced C Programming Topics

CS240: Programming in C

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

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)

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

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

CE Lecture 11

2009 S2 COMP File Operations

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

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

ENG120. Misc. Topics

Organization of a file

211: Computer Architecture Summer 2016

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

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

CSE 230 Intermediate Programming in C and C++ Input/Output and Operating System

EM108 Software Development for Engineers

C mini reference. 5 Binary numbers 12

Computer Programming Unit v

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

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

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

File I/O. Preprocessor Macros

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

CSE 12 Spring 2016 Week One, Lecture Two

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

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

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

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

C programming basics T3-1 -

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

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

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

Goals of this Lecture

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

HIGH LEVEL FILE PROCESSING

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

SWEN-250 Personal SE. Introduction to C

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

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

File Handling in C. EECS 2031 Fall October 27, 2014

The Design of C: A Rational Reconstruction (cont.)

Introduction to file management

25.2 Opening and Closing a File

CSE 12 Spring 2018 Week One, Lecture Two

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

UNIX input and output

8. Characters, Strings and Files

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

UNIX System Programming

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

C-Refresher: Session 10 Disk IO

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

Data File and File Handling

Programming & Data Structure

Fundamentals of Programming. Lecture 11: C Characters and Strings

Ch 11. C File Processing (review)

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

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

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

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

Binghamton University. CS-220 Spring Includes & Streams

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

Chapter 11 File Processing

C File Processing: One-Page Summary

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

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

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

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

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

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

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

File System User API

DATA STRUCTURES USING C

Fundamentals of Programming. Lecture 15: C File Processing

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

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

Lecture6 File Processing

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

Transcription:

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 declarations for I/O functions. There are two types of I/O stream and associated functions: Text streams: text lines of up to at least 254 characters, terminated by a newline (Linux); I/O functions take task of translating between the external and internal forms. Binary stream: written to the file or device as the program wrote them and delivered to the program exactly as they were read from the file or device; we will not consider those. One of declarations in stdio.h is for the FILE structure: a FILE is a data structure to access a stream, If a several different streams are active at a time, each will have its own FILE structure associated with it. Run time C environment provides three standard streams: stdin (a keyboard), stdout (a display) and stderr (a display). g. babic Presentation G 2 1

The printf Functions int fprintf (FILE *stream, char const *format, ) Formats the values of arguments that follow format argument according to the format codes and other characters in the format argument and resulting output goes to stream. Function printf() doesn t have the first argument and prints to the standard output stdout. There is also sprintf() function. Upon successful return, these functions return the number of characters printed. If an output error is encountered, a negative value is returned. Example: int a=1279,z; z = fprintf(stdout, Output:%d hex:%.8x octal:%o\n, a, a, a); printf( Length: %d,z); Displayed Output:1279 hex:000007ff octal:2377 Length: 36 g. babic Presentation G 3 The printf Format Codes Code Argument Meaning d or i int Print an integer value in decimal u unsigned int Print an unsigned integer value in decimal x or X unsigned int Print an unsigned integer value in hexadecimal o unsigned int Print an unsigned integer value in octal e or E double or float Print a floating-point value in exponent notation f double or float Print a floating-point value in conventional notation g or G double or float Print a floating-point value in exp. or conven. notation s char * Print a character string c int Truncated to unsigned char and print as a character p void * Print the value of the pointer Modifier Used with Means the Argument is h d, i, u, x, X, o a (possible unsigned) short integer l d, i, u, x, X, o a (possible unsigned) long integer g. babic Presentation G 4 2

Formatting Width of Numbers on Output %d print as decimal integer %6d print as decimal integer, at least 6 characters wide %f print as floating point, 6 characters after decimal point %6f print as floating point, at least 6 characters wide %.2f print as floating point, 2 characters after decimal point %6.2f print as floating point, at least 6 wide and 2 after decimal point The width of the whole number portion is for decimal integers. The character width for float includes the decimal point position. For additional details of formatting string, integers and floatingpoint values with printf() see Reek Figures 15.1, 15.2, 15.3 and 15.4. printf family of I/O functions are line formatted output functions. g. babic Presentation G 5 C I/O Functions and System Calls C program invoking printf() library call, which in turn calls write() system call. g. babic Presentation G 6 3

Common scanf Format Codes Code Meaning Argument d Read an decimal value and store as signed int * u Read as a decimal value and store as unsigned unsigned * o Read as a octal value and store as unsigned unsigned * x or X Read as a hex value and store as unsigned unsigned * e or f or g Read a single precision real value float * c Read a single character char * s Read sequence of non-whitespace characters as a character string; the string is nul-terminated array of char Modifier Used with Means the Argument is h d, u, x, X, o a (possible unsigned) short integer l d, u, x, X, o a (possible unsigned) long integer l e, f, g a double precision real value g. babic Presentation G 7 The scanf Functions int fscanf (FILE *stream, char const *format,.) Reads characters from stream, converts them according to the codes given in the format string and stores the results in the locations pointed to by the corresponding pointers in arguments that follow format. Input stops when the end of the format string is reached or input is read that does not match what the format specifies. In either case, the number of input values that were converted is returned as the function value. EOF returned if end of file reached before any value. Function scanf() doesn t have the first argument and reads from stdin. There is also sscanf() function. Example: int a, b, n; float c; n = fscanf(stdin, %d %d %f, &a, &b, &c); Input 4 23466 544.3 Outcome n 3, a 4, b 23466, c 544.3 scanf family of I/O functions are line formatted input functions. g. babic Presentation G 8 4

Moving-Head Disk Mechanism A sector (usually 512 bytes) is a basic unit of transfer (read/write) g. babic Presentation G 9 Overview of File I/O The program has to declare variable of type FILE * for each file that must be simultaneously active. To access any file, it has to be first open by calling the fopen() function. A name of a file to be accessed and how (for reading, writing or both) have to be specified in the fopen() function. Operating system and fopen() verify that the file exists, if you have permission to access in the manner specified, and then the FILE structure is initialized. The file then can be read and/or written using e.g. fprintf() or fscanf() functions. Finally, the stream is closed with the fclose() function. I/O on the standard streams stdin, stdout and stderr is simple because they do not have to be opened or closed. g. babic Presentation G 10 5

Opening File FILE *fopen(char const *name, char const *mode) name is the name of the file that should be open mode indicates how is the file to be used: I/O stream type Read Write Append Read&Write Read&Append text r w a r+ or w+ a+ to open a file for reading ( r or r+ ), the file must already exist. if a file opened for writing ( w or w+) does not exist, it will be created, while if it already exists, it will be truncated to 0 bytes length. if a file opened for appending ( a or a+ ) does not exist, it will be created, while if it already exists, it will not be truncated; in either case, data can be written to the end of the file. if successful, fopen() returns a pointer to the FILE structure (called a file descriptor), otherwise a NULL value is returned. g. babic Presentation G 11 Accessing File Unix/Linux provides a view of a file as a contiguous logical address space without any structure, just as a sequence of bytes. Once a file is opened, a file has the file location indicator associated with it and that is the offset in the file where the next read from the file or write to the file will start. After opening with r, r+, w or w+ the file location indicator has value zero, i.e. it points to the first byte of the file; after opening with a or a+, it points after the last byte of the file. After a file is open, fscanf (or fgets or fgetc) can be used to read from the file, and fprintf (or fputs or fputc) to write into the file. Each read or write starts at a location of the file location indicator and then increments the file location indicator for a number of bytes (including white space characters) read or written. Writing in the middle a file overwrites any existing characters, while writing at its end, enlarges a size of the file. 12 6

Other File I/O Functions int fflush(file *stream); fflush() forces a write of all buffered data for the given output. The open status of the file is unaffected. after writing to the file, fflush() must be called before reading from it; int fclose(file *fp); fclose() closes the file pointed to by fp, thus preventing the associated file from being accessed again, guaranteeing that any data stored in the stream buffer is correctly written to the file, and releases the FILE structure so that it can be used again with another file. fclose() also does tasks of fflush(). void rewind(file *stream); rewind() sets the file location indicator for the stream pointed to by stream to the beginning of the file. int fseek() changes a position of the file location indicator. g. babic Presentation G 13 (fileio) Example with File I/O Functions int main() { FILE *finout; int i1 = 1234, i2 = 987, i3, i; char c1[50], c2[50]; finout = fopen("testfile", "w+"); if (finout == NULL) { printf( Open TestFile failed\n"); return -1; } fprintf(finout, "%d%d", i1,i2); Output: c1=1234987 c1=1234987 c1=2469974 c1=hello c2=1234987 1234987 2469974 Hello rewind(finout); fflush(finout); fscanf(finout, "%d",&i3); fprintf(finout," %d", i3); i3=i3*2; fprintf(finout, " %d %s", i3, "Hello"); rewind(finout); fflush(finout); while(fscanf(finout,"%s", c1)!=eof) printf("\nc1=%s", c1); rewind(finout); i=0; while (fscanf(finout,"%c",&c2[i++])!=eof); c2[i]='\0'; printf("\nc2=%s", c2); fclose(finout); return; } g. babic 14 7

Redirecting stdin and stdout It is possible to redirect stdout to a file instead of the screen/monitor : Example: %lab2c > OutFile > makes that output from the program lab2c will be redirected to the file OutFile if OutFile already exists error Example: % lab2c >! OutFile! overwrites if the file OutFile already exists. It is possible to redirect stdin from a file instead of the keyboard Example: %lab2c < InFile < makes that the program gets input from the file InFile. Redirecting stdin&stdout example: % lab2c < lnfile >! OutFile1 Redirecting is a support from the operating system Linux. g. babic Presentation G 15 Character I/O Functions (included for completeness) int fgetc (FILE *stream); Reads the next character from stream (as unsigned char), returns it as the value of the function (whatever it is) as int. EOF returned, if end of file reached or error. Why is int returned instead of char? Function getchar() has empty argument list and reads from stdin. There is also getc() function identical to fgetc(). int fputc (int character, FILE *stream); Truncates the integer variable to an unsigned character and writes it to stream. EOF returned if an error occurred while writing, otherwise the character written returned as int. Function putchar() does not have the secon parameter and writes to stdout. There is also putc() function identical to fputc(). int ungetc (int character, FILE *stream); Returns a character previously read back to stream g. babic Presentation G 16 8

Unformatted Line I/O Functions (for completeness) char *fgets (char *buffer, int buffer_size, FILE *stream); Reads characters from stream and copies them into buffer. Reading stops after a newline character has been read and stored in buffer. It also stops after buffer_size-1 characters has been stored in buffer, and in this case the next fgets() will get the next character from stream. In either case, a nul byte is appended to the end of whatever is stored in the buffer. If end of file is reached before any character have been read, buffer is unchanged and fgets returns a NULL pointer, otherwise the pointer to buffer is returned. Also: gets() int *fputs (char const *buffer, FILE *stream); buffer must contain a string, i.e. expected to be nul character terminated, and its characters are written to stream. if an error occurred while writing, fputs() returns EOF, otherwise it returns a non-negative value. Also: puts() g. babic Presentation G 17 9