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

Similar documents
File IO and command line input CSE 2451

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

Standard File Pointers

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

System Software Experiment 1 Lecture 7

Input/Output and the Operating Systems

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

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

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

25.2 Opening and Closing a File

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

Introduction to file management

Input / Output Functions

2009 S2 COMP File Operations

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

PROGRAMMAZIONE I A.A. 2017/2018

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

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

File I/O. Preprocessor Macros

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

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

CS240: Programming in C

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

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

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

UNIX System Programming

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

File Handling. Reference:

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Data File and File Handling

C-Refresher: Session 10 Disk IO

EM108 Software Development for Engineers

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

C Basics And Concepts Input And Output

M.CS201 Programming language

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

Basic and Practice in Programming Lab 10

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

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

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

HIGH LEVEL FILE PROCESSING

structs as arguments

Standard C Library Functions

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)

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

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

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

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

Naked C Lecture 6. File Operations and System Calls

C File Processing: One-Page Summary

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

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

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

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

Goals of this Lecture

I/O Management! Goals of this Lecture!

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

I/O Management! Goals of this Lecture!

Organization of a file

ENG120. Misc. Topics

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

Computer Programming Unit v

IO = Input & Output 2

Engineering program development 7. Edited by Péter Vass

CE Lecture 11

Text Output and Input; Redirection

CSC 270 Survey of Programming Languages. Input and Output

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

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

Computer programming

Simple Output and Input. see chapter 7

C programming basics T3-1 -

File and Console I/O. CS449 Spring 2016

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

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

Programming & Data Structure

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

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

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

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

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

CSC 1107: Structured Programming

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

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

CP2 Revision. theme: file access and unix programs

CSC 1107: Structured Programming

Lecture 8: Structs & File I/O

Lecture 9: File Processing. Quazi Rahman

SAE1A Programming in C. Unit : I - V

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

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

File and Console I/O. CS449 Fall 2017

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.

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

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

8. Characters, Strings and Files

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

Transcription:

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 Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. So some policy from UNIX was transferred to C language UNIX treats I/O devices as file: file /dev/stdin as standard input (keyboard) file /dev/stdout as standard output (monitor) file /dev/stderr as standard error (monitor) Same as C language that treats I/O devices as file too.

Input Output Devices when we include <stdio.h> into c source it will define standard I/O with the following keyword: stdin as standard input (keyboard) file pointer stdout as standard output (monitor) file pointer stderr as standard error (monitor) file pointer those keyword is file pointer data type (FILE *) actually, many function that we already learned (printf, scanf, getchar and so on) connect with file I/O so whatever we do with I/O devices, it can do with file in the same behavior and vice versa

Input Output Devices (cont.) we can use fscanf instead of scanf scanf("%d", &num); is same as fscanf(stdin, "%d", &num); getchar and putchar can be defined in terms of getc, putc, stdin, and stdout as follows: #define getchar() getc(stdin) #define putchar(c) putc((c), stdout) we will learn about fscanf, getc and putc later in this chapter

File Access

File Access The examples so far have all read the standard input and written the standard output, which are automatically defined for a program by the local operating system. When we want to read from file or write to file we must connect those file to our resources first. The rules are simple. Before it can be read or written, a file has to be opened by the library function fopen. fopen takes an external name like a.txt or b.dat, does some housekeeping and negotiation with the operating system (details of which needn't concern us), and returns a pointer to be used in subsequent reads or writes of the file.

File pointer The returned pointer, called the file pointer, points to a structure that contains information about the file, such as the location of a buffer, the current character position in the buffer, whether the file is being read or written, and whether errors or end of file have occurred. Users don't need to know the details, because the definitions obtained from <stdio.h> include a structure declaration called FILE.

File pointer (cont.) The only declaration needed for a file pointer is exemplified by FILE *fp; FILE *fopen(char *name, char *mode); This says that fp is a pointer to a FILE, and fopen returns a pointer to a FILE. Notice that FILE is a type name, like int, not a structure tag; it is defined with a typedef. (will be explained later in chapter of complex data type) The call to fopen in a program is fp = fopen(name, mode);

File pointer (cont.) The first argument of fopen is a character string containing the name of the file. The second argument is the mode, also a character string, which indicates how one intends to use the file. Allowable modes include read ("r"), write ("w"), and append ("a"). Some systems distinguish between text and binary files; for the latter, a "b" must be appended to the mode string.

File pointer (cont.) If a file that does not exist is opened for writing or appending, it is created if possible. Opening an existing file for writing causes the old contents to be discarded, while opening for appending preserves them. Trying to read a file that does not exist is an error, and there may be other causes of error as well, like trying to read a file when you don't have permission. If there is any error, fopen will return NULL.

File pointer (cont.) We need file pointer for specific which file we will perform an action. And pass it as argument to function of file. fscanf(fp1, "%d", &num); fprintf(fp2, "%d", num); fp1 and fp2 are file pointer of specific file. fp1 and fp2 may point to the difference file.

Function of File

General assumption Many of function of file have function name start with f; fopen fscanf fprintf fopen will return file pointer if successes connect to file and return NULL if has some error. Other function need file pointer as argument (usually, first argument).

fopen prototype FILE *fopen(const char *filename, const char *mode); description fopen opens the named file, and returns a stream, or NULL if the attempt fails. parameters filename -> file name mode -> mode to access

fopen (cont.) mode r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists) + suffix indicates update mode that permits reading and writing the same file; fflush or a file-positioning function must be called between a read and a write or vice versa. to treat file as binary contents must end mode with b "rb" "w+b"

fopen (cont.) example fp = fopen("a.txt", "r"); // open with read only fp = fopen("b.txt", "w"); // open with write only (override) fp = fopen("c.txt", "a"); // open with write only (append) fp = fopen("d.txt", "a+"); // open with read & write // (append only when write) fp = fopen("e.txt", "rb"); // open with read only // (contents is binary)

fclose prototype int fclose(file *stream); description fclose flushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream. It returns EOF if any errors occurred, and zero otherwise. parameters stream -> file pointer example fclose(fp); // can use if to check successful of close // because EOF is not zero value

fflush prototype int fflush(file *stream); description On an output stream, fflush causes any buffered but unwritten data to be written on an input stream, the effect is undefined. It returns EOF for a write error, and zero otherwise. fflush(null) flushes all output streams. parameters stream -> file pointer example fflush(stdout); // flush buffer of standard output

fprintf prototype int fprintf(file *stream, const char *format,...); description fprintf converts and writes output to stream under the control of format. The return value is the number of characters written, or negative if an error occurred. parameters stream -> file pointer format -> output format same as printf... -> variable list

fprintf (cont.) example fprintf(stdout, "%d\n", num); // print out to // standard output fprintf(fp, "%d\n", num); // print out to // file pointer fp fprintf(fp, "%s is %d years old.\n", name, age);

fscanf prototype int fscanf(file *stream, const char *format,...); description fscanf reads from stream under control of format, and assigns converted values through subsequent arguments, each of which must be a pointer. It returns when format is exhausted. fscanf returns EOF if end of file or an error occurs before any conversion; otherwise it returns the number of input items converted and assigned. parameters stream -> file pointer format -> output format same as scanf... -> variable list (start with & for non-array variable)

fscanf (cont.) example fscanf(stdin, "%d %d", &a, &b); fscanf(fp, "%d %d", &a, &b); fscanf(fp, "%s %d", name, &age); // read from // standard input // read from // file pointer fp

fgetc prototype int fgetc(file *stream); description fgetc returns the next character of stream as an unsigned char (converted to an int), or EOF if end of file or error occurs. parameters stream -> file pointer example ch = fgetc(fp); ch = fgetc(stdin); // same as ch = getchar();

fgets prototype char *fgets(char *s, int n, FILE *stream); description fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered; the newline is included in the array, which is terminated by '\0'. fgets returns s, or NULL if end of file or error occurs. parameters s -> string variable for retrieve data from stream n -> at most n-1 characters stream -> file pointer

fgets (cont.) example char str[255]; // string buffer declaration fgets(str, 255, fp); // read line from // file pointer fp fgets(str, 255, stdin); // read line from // standard input plus protections against // a buffer overflow vulnerability that gets // doesn't protect sp = fgets(str, 255, fp); // sp must be char pointer // and is not array variable

fputc prototype int fputc(int c, FILE *stream); description fputc writes the character c (converted to an unsigend char) on stream. It returns the character written, or EOF for error. parameters c -> character to be written stream -> file pointer example fputc('a', fp); // write a to file pointer fp

fputs prototype int fputs(const char *s, FILE *stream); description fputs writes the string s (which need not contain '\n') on stream. It returns nonnegative, or EOF for an error. parameters s -> string to be written stream -> file pointer example fputs("abcd", fp);// write abcd to file pointer fp

fread prototype size_t fread(void *ptr, size_t size, size_t nobj, FILE *stream); description fread reads from stream into the array ptr at most nobj objects of size size. fread returns the number of objects read; this may be less than the number requested. feof and ferror must be used to determine status. Usually, stream may open with b (binary) mode to prevent unexpected behavior (depend on OS).

fread (cont.) parameters prt -> pointer to variable size -> size of each object nobj -> number of object stream -> file pointer example fread(buff, sizeof (char), 255, fp);

fwrite prototype size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *stream); description fwrite writes, from the array ptr, nobj objects of size size on stream. It returns the number of objects written, which is less than nobj on error. parameters prt -> pointer to variable size -> size of each object nobj -> number of object stream -> file pointer

fwrite (cont.) example fwrite(buff, sizeof (char), 255, fp); // usually, 255 may be the size that return from fread

feof prototype int feof(file *stream); description feof returns non-zero if the end of file indicator for stream is set. parameters stream -> file pointer example while(!feof(fp)){ // some code that read content from fp }

ferror prototype int ferror(file *stream); description ferror returns non-zero if the error indicator for stream is set. parameters stream -> file pointer example if(ferror(fp)) fprintf(stderr, "There are some error!!!\n");

Full example #include <stdio.h> #define BUFF_SIZE 255 #define FILE_NAME "a.txt" int main(){ FILE *fp; char buff[buff_size]; if(!(fp = fopen(file_name, "r"))){ fprintf(stderr, "Cannot open file %s!!!\n", FILE_NAME); return -1; } while(fgets(buff, BUFF_SIZE, fp)) printf("%s", buff); fclose(fp); return 0; }

Notable fgets includes new-line character but gets excludes that. size_t is pre-defined datatype in <stddef.h> with // for 32-bit CPU typedef unsinged long size_t; // for 64-bit CPU or 32-bit CPU with x86_64 typedef unsigned long long size_t;

Notable (cont.) When use fread on MS Windows OS fread will stop read when meet new-line character if stream was opened without b mode. this behavior doesn't occur on UNIX-like OS. retrieve EOF from keyboard because keyboard is endless stream, it doesn't have EOF. we can send End of Transmission signal to program by use ^Z (ctrl-z) on MS Windows OS ^D (ctrl-d) on UNIX-like OS

Notable (cont.) fflush is important in UNIX-like OS treat stdout console(tty) as buffered stream consider the following code printf("input n : "); scanf("%d", &n); in UNIX-like OS the sentence "Input n : " never print out to monitor before scanf statements because it was kept in buffer and not print out to monitor until meet '\n'.

Notable (cont.) fflush is important in UNIX-like OS (cont.) for UNIX-like OS the previous code must be written in following code printf("input n : "); fflush(stdout); scanf("%d", &n); fflush force flushing buffer to monitor. this behavior may not occur on some console type such as cmd on MS Windows OS. treat stdout console(cmd) as un-buffered stream. to guarantee printf was printed out fflush may be used after printf that doesn't end with '\n' in its format.

I/O Redirection

Command-line redirection We can change standard I/O to redirect to specific file redirect standard input use < on command line myproc < input.txt redirect standard output use > on command line myproc > output.txt redirect both standard I/O myproc < input.txt > output.txt redirect standard error use 2> on command line (2 indicates standard error) myproc 2> error.txt redirect standard error to standard output (1 indicates standard output) myproc 2>&1

Command-line redirection (cont.) The output from some program can be input of another program, called piping. use to pipe output to be input of another program myproc01 myproc02

Command-line arguments

Command-line arguments The parameters of main function are argc and argv argc is number of arguments (include program name) that separated by white-space argv is array of arguments value example int main(int argc, char *argv[]){ // some code }

Command-line arguments (cont.) pass argument on command-line, consider below example: echo hello, world By convention, argv[0] is the name by which the program was invoked, so argc is at least 1. If argc is 1, there are no command-line arguments after the program name. In the example above, argc is 3, and argv[0], argv[1], and argv[2] are "echo", "hello,", and "world" respectively. The first optional argument is argv[1] and the last is argv[argc-1]; additionally, the standard requires that argv[argc] be a null pointer.

Command-line arguments (cont.)

Example #include <stdio.h> int main(int argc, char *argv[]){ FILE *fp = stdin; int width, height; if((argc > 1) &&!(fp = fopen(argv[1], "r"))){ fprintf(stderr, "Cannot open file %s!!!\n", argv[1]); return -1; } printf("input (width height): "); fflush(stdout); fscanf(fp, "%d %d", &width, &height); if(fp!= stdin) printf("%d %d\n", width, height); printf("area = %d\n", width * height); if(fp!= stdin) fclose(fp); return 0; }

Reference http://www.tutorialspoint.com/cprogramming/c_overview.htm http://www.cprogramming.com/tutorial/cfileio.html Brian W., Dennis M., C Programming Language: second edition.