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

Similar documents
File IO and command line input CSE 2451

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

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

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

Input/Output and the Operating Systems

Programming & Data Structure

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

C-Refresher: Session 10 Disk IO

File Handling. 21 July 2009 Programming and Data Structure 1

System Software Experiment 1 Lecture 7

CS240: Programming in C

Organization of a file

Standard File Pointers

Standard C Library Functions

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

C programming basics T3-1 -

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

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

CSC 1107: Structured Programming

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

CSC 1107: Structured Programming

UNIX System Programming

Fundamentals of Programming. Lecture 10 Hamed Rasifard

IO = Input & Output 2

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

Character Arrays. strlen("hello, world"); /* string constant */ strlen(array); /* char array[100]; */ strlen(ptr); /* char *ptr; */

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

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

Pointers and File Handling

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

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

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

2009 S2 COMP File Operations

CP2 Revision. theme: file access and unix programs

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

EM108 Software Development for Engineers

Course organization. Course introduction ( Week 1)

8. Characters, Strings and Files

25.2 Opening and Closing a File

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

Text Output and Input; Redirection

Laboratory: USING FILES I. THEORETICAL ASPECTS

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

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Simple Output and Input. see chapter 7

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

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

CSC 270 Survey of Programming Languages. Input and Output

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

structs as arguments

Engineering program development 7. Edited by Péter Vass

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

PROGRAMMAZIONE I A.A. 2017/2018

Programming Fundamentals

Introduction to file management

C PROGRAMMING. Characters and Strings File Processing Exercise

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

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

C FILE Type. Basic I/O in C. Accessing a stream requires a pointer of type FILE.

EL2310 Scientific Programming

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

File I/O. Preprocessor Macros

HIGH LEVEL FILE PROCESSING

Computer Programming Unit v

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

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

Lecture 03 Bits, Bytes and Data Types

C FILE Type. Basic I/O in C. Accessing a stream requires a pointer variable of type FILE.

Data File and File Handling

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Input / Output Functions

M.CS201 Programming language

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

Intermediate Programming, Spring 2017*

C Basics And Concepts Input And Output

File I/O. Last updated 10/30/18

File I/O BJ Furman 23OCT2010

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

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

Binghamton University. CS-220 Spring Includes & Streams

Today s Learning Objectives

Computational Methods of Scientific Programming Fall 2007

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

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)

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

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

Procedural Programming

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

CE Lecture 11

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

Lecture 9: File Processing. Quazi Rahman

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

ENG120. Misc. Topics

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

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.

EL2310 Scientific Programming

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Introduction. Files. 3. UNIX provides a simple and consistent interface to operating system services and to devices. Directories

Transcription:

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

Lecture 5: Files, I/O 0IGXYVI*MPIW 0 opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments files are treated as data streams keyboard, screen, printer,... are also treated as streams from the C perspective writing/reading from a file is the same as writing to the screen/reading from the keyboard

File opening and closing Basic I/O functions included in stdio.h Example: printf function (writes something to stdout)

File opening and closing Basic I/O functions included in stdio.h Example: printf function (writes something to stdout) Basic file operations: FILE *in-file; in-file = fopen\( input.txt, r \);... /* read stuff from input.txt */ status = fclose(in-file); if (status!= 0) printf\( File closing error.\\n \);

eclare variable of type (pointer to) FILE File opening and closing Basic I/O functions included in stdio.h Example: printf function (writes something to stdout) Basic file operations: FILE *in-file; in-file = fopen(input.txt, r );... /* read stuff from input.txt */ status = fclose(in-file); if (status!= 0) printf (File closing error.\n);

File opening and closing Basic I/O functions included in stdio.h Example: printf function (writes something to stdout) Basic file operations: fopen opens the file input.txt in read mode ( r ) and returns a FILE *in-file; pointer to that file. in-file is now linked to input.txt. in-file = fopen\( input.txt, r \);... /* read stuff from input.txt */ status = fclose(in-file); if (status!= 0) printf\( File closing error.\\n \); Declare variable of type (pointer to) FILE

File opening and closing Basic I/O functions included in stdio.h Example: printf function (writes something to stdout) Basic file operations: Declare variable of type (pointer to) FILE fopen opens the file input.txt in read mode ( r ) and returns a FILE *in-file; pointer to that file. in-file is now linked to input.txt. in-file = fopen\( input.txt, r \);... /* read stuff from input.txt */ status = fclose(in-file); if (status!= 0) printf\( File closing error.\\n \); fclose closes the file connected to in-file and if successful returns 0.

File opening and closing Basic I/O functions included in stdio.h Example: printf function (writes something to stdout) Basic file operations: Declare variable of type (pointer to) FILE fopen opens the file input.txt in read mode ( r ) and returns a FILE *in-file; pointer to that file. in-file is now linked to input.txt. in-file = fopen\( input.txt, r \);... /* read stuff from input.txt */ status = fclose(in-file); if (status!= 0) printf\( File closing error.\\n \); fclose closes the file connected to in-file and if successful returns 0. There are 3 pre-opened and pre-defined files: stdin (keyboard), stdout, stderr (screen)!

Possible mode specifiers for fopen r Open a text file for reading w Create a text file for writing a Append to a text file rb Open a binary file for reading wb Open a binary file for writing ab Append to a binary file r+ Open a text file for read/write w+ Create a text file for read/write a+ Append or create a text file for read/write r+b Open a binary file for read/write w+b Create a binary file for read/write a+b Append a binary file for read/write (Binary files are beyond the scope of this course)

Read/write functions (ASCII files) for single characters: int fgetc(file *file-var) int fputc(int character, FILE *file-var)

Read/write functions (ASCII files) for single characters: int fgetc(file *file-var) int fputc(int character, FILE *file-var) for whole strings: char *fgets(char *string, int size, FILE *file-var) int fputs(char *string, FILE *file-var)

Read/write functions (ASCII files) for single characters: int fgetc(file *file-var) int fputc(int character, FILE *file-var) for whole strings: char *fgets(char *string, int size, FILE *file-var) int fputs(char *string, FILE *file-var) for everythings else (conversion routines): int scanf(char *format,...) int fscanf(file *file-var, char *format,...) int sscanf(char *buffer, char *format,...) int printf(char *format,...) int fprintf(file *file-var, char *format,...) int sprintf(char *buffer, char *format,...) (stdin) (file) (string) (stdout) (file) (string)

Read/write functions (ASCII files) for single characters: int fgetc(file *file-var) int fputc(int character, FILE *file-var) for whole strings: char *fgets(char *string, int size, FILE *file-var) int fputs(char *string, FILE *file-var) for everythings else (conversion routines): int scanf(char *format,...) int fscanf(file *file-var, char *format,...) int sscanf(char *buffer, char *format,...) int printf(char *format,...) int fprintf(file *file-var, char *format,...) int sprintf(char *buffer, char *format,...) (stdin) (file) (string) (stdout) (file) (string) Special constant EOF (end of file) also defined in stdio.h

Read/write functions (ASCII files) for single characters: int fgetc(file *file-var) int fputc(int character, FILE *file-var) for whole strings: char *fgets(char *string, int size, FILE *file-var) int fputs(char *string, FILE *file-var) for everythings else (conversion routines): int scanf(char *format,...) int fscanf(file *file-var, char *format,...) int sscanf(char *buffer, char *format,...) int printf(char *format,...) int fprintf(file *file-var, char *format,...) int sprintf(char *buffer, char *format,...) (stdin) (file) (string) (stdout) (file) (string) Special constant EOF (end of file) also defined in stdio.h (for more information see e.g.: http://www.elook.org/programming/c/stdio.html )

Example: read string from keyboard fgets(string-name, sizeof(string-name), stdin)

Example: read string from keyboard fgets(string-name, sizeof(string-name), stdin) sizeof function: returns the size (in bytes) of something

Example: read string from keyboard fgets(string-name, sizeof(string-name), stdin) sizeof function: returns the size (in bytes) of something #include<string.h> char line[100]; int main() { printf\\\( Enter a word: \\\); fgets(line, sizeof(line), stdin); printf\\\( Length of word is %d\\\\n, strlen(line)); return(0);

Example: read string from keyboard fgets(string-name, sizeof(string-name), stdin) sizeof function: returns the size (in bytes) of something #include<string.h> char line[100]; int main() { printf\\\( Enter a word: \\\); fgets(line, sizeof(line), stdin); printf\\\( Length of word is %d\\\\n, strlen(line)); return(0); fgets includes the newline character '\n' in the string

Example: read string from keyboard (2) #include<string.h> char line[100]; int main() { printf\( Enter a word: \); fgets(line, sizeof(line), stdin); /* Better: strip of the newline character */ line[strlen(line)-1] = '\0'; printf\( Length of word is %d\\n, strlen(line)); return(0);

Example: read string from keyboard (2) #include<string.h> char line[100]; int main() { printf\( Enter a word: \); fgets(line, sizeof(line), stdin); /* Better: strip of the newline character */ line[strlen(line)-1] = '\0'; printf\( Length of word is %d\\n, strlen(line)); return(0);

Example: read string from keyboard (2) #include<string.h> char line[100]; int main() { printf\( Enter a word: \); fgets(line, sizeof(line), stdin); /* Better: strip of the newline character */ line[strlen(line)-1] = '\0'; printf\( Length of word is %d\\n, strlen(line)); return(0); Notice the difference between size and length sizeof(line) = number of bytes allocated for line = 100 strlen(line) = number of characters before '\0' (end of string)

Reading numbers using scanf int value; printf\( Enter value: \); scanf\( %d, &value\);

Reading numbers using scanf int value; printf\( Enter value: \); scanf\( %d, &value\); Note: argument of scanf has to be a pointer!

Reading numbers using scanf int value; printf\( Enter value: \); scanf\( %d, &value\); Can be unreliable. If input doesn't match required format the input stream can be messed up! Note: argument of scanf has to be a pointer!

Reading numbers using scanf int value; printf\( Enter value: \); scanf\( %d, &value\); Can be unreliable. If input doesn't match required format the input stream can be messed up! Note: argument of scanf has to be a pointer! Better: using fgets/sscanf int value; char line[100]; printf\( Enter value: \); fgets(line,sizeof(line), stdin); sscanf\(line, %d, &value\);

Reading numbers using scanf int value; printf\( Enter value: \); scanf\( %d, &value\); Can be unreliable. If input doesn't match required format the input stream can be messed up! Note: argument of scanf has to be a pointer! Better: using fgets/sscanf int value; char line[100]; printf\( Enter value: \); fgets(line,sizeof(line), stdin); sscanf\(line, %d, &value\); If format doesn't match input, the input string is still available for further analysis!

Reading numbers using scanf int value; printf\( Enter value: \); scanf\( %d, &value\); Can be unreliable. If input doesn't match required format the input stream can be messed up! Note: argument of scanf has to be a pointer! Better: using fgets/sscanf int value; char line[100]; printf\( Enter value: \); fgets(line,sizeof(line), stdin); sscanf\(line, %d, &value\); If format doesn't match input, the input string is still available for further analysis! Format specifiers for scanf, sscanf, fscanf are the same as for printf, sprintf, fprinf, except for double scanf requires %lf!

Possible problem with scanf main() { int input=0; while(input<1) { printf\( Please enter a positive integer: \); scanf\( %d,&input); printf\( The number you entered was: %d\\n,&input); return(0); What happens if the user (accidentally) enters a character? Why?

Possible problem with scanf main() { int input=0; while(input<1) { printf\( Please enter a positive integer: \); scanf\( %d,&input); printf\( The number you entered was: %d\\n,&input); return(0); What happens if the user (accidentally) enters a character? Why? if scanf cannot match input to format string it does not advance the input stream, i.e. in the above example scanf reads the same (wrong) input again and again.

Command line arguments main(int argc, char *argv[]) { printf\( Number of command line arguments: %d\\n, argc-1\); while (argc > 1){ printf\( %s, argv[1]\); --argc; ++argv;

Command line arguments main(int argc, char *argv[]) { printf\( Number of command line arguments: %d\\n, argc-1\); while (argc > 1){ printf\( %s, argv[1]\); --argc; ++argv; Always declare main like this if you want to use command line arguments!

Command line arguments main(int argc, char *argv[]) { printf\( Number of command line arguments: %d\\n, argc-1\); while (argc > 1){ printf\( %s, argv[1]\); --argc; ++argv; argc indicates the number of command line arguments argv[i] contains the i'th argument argv[0] contains the program name argc >= 1 Always declare main like this if you want to use command line arguments!

Example: password protected program #include<stdlib.h> #include<string.h> char passwd[8] = "CP3065JS"; main(int argc, char *argv[]) { if (argc!= 2) { printf("specify password!\n"); exit(1); if ( strcmp(argv[1], passwd) == 0 ) printf("access Permitted\n"); else { printf("access denied\n"); exit(1); /* now the real program starts */ printf("this program doesn't really do anything.\n"); return(0);

Example: searc hfile.c /* Search specified file for specified character. */ #include <stdio.h> #include <stdlib.h> main(int argc, char *argv[]) { FILE *fp; /* file pointer */ char ch; searchfile.c: searches for specified character in specified file /* check for correct number of command line arguments */ if(argc!=3) { printf("usage: %s <filename> <ch>\n", argv[0]); exit(1); /* exits function is part of stdlib.h */ /* open file for input */ fp = fopen(argv[1], "r"); if(fp == NULL) { printf("cannot open file \n"); exit(1); /* look for character */ while ( (ch=fgetc(fp) )!= EOF ) if (ch == *argv[2]) { printf("%c found\n", ch); break; fclose(fp); return(0);

specified character Example: searc hfile.c /* Search specified file for specified character. */ #include <stdio.h> #include <stdlib.h> main(int argc, char *argv[]) { FILE *fp; /* file pointer */ char ch; searchfile.c: searches for in specified file /* check for correct number of command line arguments */ if(argc!=3) { printf("usage: %s <filename> <ch>\n", argv[0]); exit(1); /* exits function is part of stdlib.h */ /* open file for input */ fp = fopen(argv[1], "r"); if(fp == NULL) { printf("cannot open file \n"); exit(1); /* look for character */ while ( (ch=fgetc(fp) )!= EOF ) if (ch == *argv[2]) { printf("%c found\n", ch); break; fclose(fp); return(0); Exercise: make searchfile.c count the number of occurrences of a specified character