CSC 1107: Structured Programming

Similar documents
CSC 1107: Structured Programming

Course organization. Course introduction ( Week 1)

File IO and command line input CSE 2451

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

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

25.2 Opening and Closing a File

CSC 270 Survey of Programming Languages. Input and Output

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

Unit 4. Input/Output Functions

2009 S2 COMP File Operations

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

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

Input/Output and the Operating Systems

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

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

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

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

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

Where we are Distributed and Parallel Technology. Union Types. A Tree Structure. t tag node. C Revision (Part II)

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

Input / Output Functions

EL2310 Scientific Programming

Fundamentals of Programming. Lecture 11: C Characters and Strings

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

EL2310 Scientific Programming

1/31/2018. Overview. The C Programming Language Part 2. Basic I/O. Basic I/O. Basic I/O. Conversion Characters. Input/Output Structures and Arrays

Simple Output and Input. see chapter 7

Standard File Pointers

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

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

Programming in C Quick Start! Biostatistics 615 Lecture 4

Should you know scanf and printf?

Advanced C Programming Topics

Text Output and Input; Redirection

F28HS2 Hardware-Software Interface. Lecture 2: Programming in C - 2

211: Computer Architecture Summer 2016

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

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

Input/Output: Advanced Concepts

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)

System Software Experiment 1 Lecture 7

EM108 Software Development for Engineers

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

THE FUNDAMENTAL DATA TYPES

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

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

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

Fundamentals of Programming

Fundamental of Programming (C)

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

CS240: Programming in C

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

C PROGRAMMING. Characters and Strings File Processing Exercise

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

Input/output functions

SU 2017 May 11/16 LAB 2: Character and integer literals, number systems, character arrays manipulation, relational operator

Input/Output Week 5:Lesson 16.1

Standard C Library Functions

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

CSC 1107: Structured Programming

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Introduction to Computing Lecture 03: Basic input / output operations

UNIT-I Input/ Output functions and other library functions

Basic and Practice in Programming Lab 10

CpSc 1010, Fall 2014 Lab 10: Command-Line Parameters (Week of 10/27/2014)

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

SWEN-250 Personal SE. Introduction to C

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Chapter 8 - Characters and Strings

File I/O. Preprocessor Macros

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

Standard I/O in C and C++

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

UNIX System Programming

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

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

printf("%c\n", character); printf("%s\n", "This is a string"); printf("%s\n", string); printf("%s\n",stringptr); return 0;

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

BSM540 Basics of C Language

Today s Learning Objectives

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

Introduction to string

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

Computer Programming Unit v

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

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

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

CSE 303 Lecture 15. C File Input/Output (I/O) reading: Programming in C Ch. 16; Appendix B pp

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Multiple Choice Questions ( 1 mark)

Should we delete all the files? (Example) From last lecture: Why use a file at all? Asst 1a. Assignment 1. Sample code.

Organization of a file

LESSON 4. The DATA TYPE char

Transcription:

CSC 1107: Structured Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1107 http://muele.mak.ac.ug block A, level 3, department of computer science Kizito (Makerere University) CSC 1107 November, 2017 1 / 15

Overview 1 Standard Input and Output Formatted Output printf() Formatted Input scanf(), sscanf() Command Line I/O Redirection File Access 2 Assignment Approximating Mathematical Constant, π Kizito (Makerere University) CSC 1107 November, 2017 2 / 15

Standard Input and Output Standard Input and Output The library <stdio.h> implements a simple model of input and output int getchar(void); reads one character at a time from the standard input int putchar(int c); puts the character c on the standard output Returns EOF for end of file or error If your source file refers to an input/output library function, it must contain the directive: #include <stdio.h> Kizito (Makerere University) CSC 1107 November, 2017 3 / 15

Standard Input and Output Example lower.c #include <stdio.h> /* getchar(), putchar() */ #include <ctype.h> int main() /* lower: convert input to lower case */ { int c; while ((c = getchar())!= EOF) putchar(tolower(c)); /* tolower() defined in ctype.h */ return 0; Kizito (Makerere University) CSC 1107 November, 2017 4 / 15

Formatted Output printf() Formatted Output printf() We have already used printf() in previous examples: int printf(char *format, arg1, arg2,...); Converts, formats, and prints its arguments on the standard output under control of the format It returns the number of characters printed Each conversion specification begins with a % and ends with a conversion character Between the % and the conversion character there may be, in order: 1 A minus sign, which specifies left adjustment of the converted argument 2 A number that specifies the minimum field width 3 A period, which separates the field width from the precision 4 A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of a floating-point value, or the minimum number of digits for an integer 5 An h if the integer is to be printed as a short, or l if as a long Kizito (Makerere University) CSC 1107 November, 2017 5 / 15

Formatted Output printf() Characters Basic printf Conversions Characters Argument Type; Printed As d,i int; decimal number o int; unsigned octal number (without a leading zero) x,x int; unsigned hexadecimal number (without a leading 0x or 0X) u int; unsigned decimal number c int; single character s char *; print characters from the string f double; m.dddddd e,e double; m.dddddde ± xx or m.dddddde ± xx g,g double; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f p void *; pointer % no argument is converted; print a % Kizito (Makerere University) CSC 1107 November, 2017 6 / 15

Formatted Output printf() Examples :%x: :1f: :%.3e: :1.235e+08: :%s: :hello, world: :%10s: :hello, world: :%.10s: :hello, wor: :%-10s: :hello, world: :%s.15: :hello, world: :%s-15: :hello, world : :%15.10s: : hello, wor: :%-15.10s: :hello, wor : Kizito (Makerere University) CSC 1107 November, 2017 7 / 15

Formatted Input scanf(), sscanf() Formatted Input scanf(), sscanf() scanf() reads characters from the standard input, interprets them according to the specification in format, and stores the results through the remaining arguments sscanf() reads from a string instead of the standard input The arguments must be pointers int scanf(char *format,...) int sscanf(char *string, char *format, arg 1, arg 2,...) The format string may contain: 1 Blanks or tabs, which are not ignored 2 Ordinary characters (not %), which are expected to match the next non-white space character of the input 3 Conversion specifications, consisting of the character %, an optional assignment suppression character *, an optional number specifying a maximum field width, an optional h, l or L indicating the width of the target, and a conversion character Kizito (Makerere University) CSC 1107 November, 2017 8 / 15

Formatted Input scanf(), sscanf() Characters Basic scanf Conversions Characters Argument Type; Input Data d int *; decimal integer i int *; integer. May be in octal (leading 0) or hexadecimal (leading 0x or 0X) o int *; octal integer (with or without leading zero) u unsigned int *; unsigned decimal integer x int *; hexadecimal integer (with or without leading 0x or 0X) c char *; character s char *; character string (not quoted) 1s char *; non-white space character e,f,g float *; floating-point number with optional sign, optional decimal point and optional exponent % no assignment is made; literal % Kizito (Makerere University) CSC 1107 November, 2017 9 / 15

Formatted Input scanf(), sscanf() Formatted Input scanf(), sscanf() Examples 1 Rudimentary calculator #include <stdio.h> main() { double sum = 0, v; while (scanf("%lf", &v) == 1) printf("\t%.2f\n", sum += v); 2 Suppose input lines should contain dates of a certain form while (getline(line, sizeof(line)) > 0) if (sscanf(line, "%d %s %d", &day, monthname, &year) == 3) printf("valid: %s\n", line); /* 2 November 2017 form */ else if (sscanf(line, "%d/%d/%d", &month, &day, &year) == 3) printf("valid: %s\n", line); /* mm/dd/yy form */ else printf("invalid: %s\n", line); /* invalid form */ Kizito (Makerere University) CSC 1107 November, 2017 10 / 15

Formatted Input scanf(), sscanf() Formatted Input scanf(), sscanf() Examples 1 Rudimentary calculator #include <stdio.h> main() { double sum = 0, v; while (scanf("%lf", &v) == 1) printf("\t%.2f\n", sum += v); 2 Suppose input lines should contain dates of a certain form while (getline(line, sizeof(line)) > 0) if (sscanf(line, "%d %s %d", &day, monthname, &year) == 3) printf("valid: %s\n", line); /* 2 November 2017 form */ else if (sscanf(line, "%d/%d/%d", &month, &day, &year) == 3) printf("valid: %s\n", line); /* mm/dd/yy form */ else printf("invalid: %s\n", line); /* invalid form */ Kizito (Makerere University) CSC 1107 November, 2017 10 / 15

Command Line I/O Redirection Command Line I/O Redirection Input redirection: prog < input_file Input redirection from another program: prog other_prog Output redirection: prog > output_file Output redirection (append): prog >> output_file Kizito (Makerere University) CSC 1107 November, 2017 11 / 15

File Access File Access FILE *fopen(char *name, char *mode); int getc(file *fp); getchar() getc(stdin) int putc(int c, FILE *fp); putchar(c) putc(c, stdout) int fscanf(file *fp, char *format,...); int fprintf(file *fp, char *format,...); int fclose(file *fp); Kizito (Makerere University) CSC 1107 November, 2017 12 / 15

File Access Line Input, Output, and Error Handling Line I/O char *fgets(char *line, FILE *fp); int fputs(char *line, FILE *fp); Error Handling int ferror(file *fp); int feof(file *fp); Kizito (Makerere University) CSC 1107 November, 2017 13 / 15

File Access File Access Example copyfile.c 1. #include <stdio.h> 2. 3. int main(int argc, char *argv[]) { /* main() can have arguments! */ 4. FILE *fin, *fout; 5. 6. if (argc == 1) { 7. fprintf(stderr, "No file supplied!\n"); 8. return 1; 9. else if ((fin = fopen(*++argv, "r")) == NULL) { 10. fprintf(stderr, "Can t open file %s for reading\n", argv[1]); 11. return 1; 12. else if (argc > 2 && (fout = fopen(*++argv, "w")) == NULL) { 13. fprintf(stderr, "Can t open file %s for writing\n", argv[2]); 14. fclose(fin); 15. return 2; 16. else if (argc == 2) 17. fout = stdout; 18. for (int c; (c = getc(fin))!= EOF; ) /* copy the file */ 19. putc(c, fout); 20. fclose(fin); 21. if (fout!= stdout) fclose(fout); 22. return 0; 23. Kizito (Makerere University) CSC 1107 November, 2017 14 / 15

Assignment Approximating Mathematical Constant, π Assignment IV Functions Approximating Mathematical Constant π = 3.14159 26535 89793 23846 26433 83279... Using Functions in the C Language #include <stdio.h> main() { // Use pi() to estimate and print π double pi() { // Use power() in the computation of π int power(int x, int n) { // Compute and return x n π Series Due date π = 2 3(1 1 3 3 + 1 5 3 2 1 7 3 3 + ) 1 = 2 2 (4k)!(1103+26390k) π 9801 k=0 (k!) 4 396 4k Thur 9 th Nov, 2017 Some π approximations: 355 113 gives more exact digits? 3 1, 22 7, 333 106, 355 113, 103993 33102, 104348 33215, 208341 66317, 312689 99532, 833719 265381, 1146408 364913, 4272943 1360120, 5419351 1725033 Test your program correct to at least 14 decimal places Kizito (Makerere University) CSC 1107 November, 2017 15 / 15

Assignment Approximating Mathematical Constant, π Assignment IV Functions Approximating Mathematical Constant π = 3.14159 26535 89793 23846 26433 83279... Using Functions in the C Language #include <stdio.h> main() { // Use pi() to estimate and print π double pi() { // Use power() in the computation of π int power(int x, int n) { // Compute and return x n π Series Due date π = 2 3(1 1 3 3 + 1 5 3 2 1 7 3 3 + ) 1 = 2 2 (4k)!(1103+26390k) π 9801 k=0 (k!) 4 396 4k Thur 9 th Nov, 2017 Some π approximations: 355 113 gives more exact digits? 3 1, 22 7, 333 106, 355 113, 103993 33102, 104348 33215, 208341 66317, 312689 99532, 833719 265381, 1146408 364913, 4272943 1360120, 5419351 1725033 Test your program correct to at least 14 decimal places Kizito (Makerere University) CSC 1107 November, 2017 15 / 15