EXAMINATION REGULATIONS and REFERENCE MATERIAL for ENCM 339 Fall 2017 Section 01 Final Examination

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

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

System Software Experiment 1 Lecture 7

Input/Output and the Operating Systems

Introduction to file management

C-Refresher: Session 10 Disk IO

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

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

C mini reference. 5 Binary numbers 12

PROGRAMMAZIONE I A.A. 2017/2018

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

Slide Set 15 (Complete)

25.2 Opening and Closing a File

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

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

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

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

Standard C Library Functions

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

CS240: Programming in C

HIGH LEVEL FILE PROCESSING

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

Standard File Pointers

ECE551 Midterm Version 1

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

University of Calgary Department of Electrical and Computer Engineering ENCM 339 Lecture Section 01 Instructor: Steve Norman

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

CP2 Revision. theme: file access and unix programs

I.D. NUMBER SURNAME OTHER NAMES

C programming basics T3-1 -

Procedural Programming

ECE551 Midterm Version 1

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

University of Calgary Department of Electrical and Computer Engineering ENCM 335 Instructor: Steve Norman

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

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

ECE551 Midterm Version 2

SAE1A Programming in C. Unit : I - V

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

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

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

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

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

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

Exercise Session 3 Systems Programming and Computer Architecture

School of Computer Science & Software Engineering The University of Western Australia. Mid-Semester Test September 2017

Engineering program development 7. Edited by Péter Vass

2009 S2 COMP File Operations

Fundamentals of Programming & Procedural Programming

Input / Output Functions

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

Programming & Data Structure

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

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

M.CS201 Programming language

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

Organization of a file

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

Ch 11. C File Processing (review)

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

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

CSCI 171 Chapter Outlines

University of Calgary Department of Electrical and Computer Engineering ENCM 339: Programming Fundamentals, Section 01 Instructor: Steve Norman

Lab # 4. Files & Queues in C

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. Preprocessor Macros

Laboratory: USING FILES I. THEORETICAL ASPECTS

ECE 551D Spring 2018 Midterm Exam

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

C File Processing: One-Page Summary

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

Chapter 11 File Processing

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

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

Do not turn this page until you have received the signal to start.

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

Text Output and Input; Redirection

CS240: Programming in C

ENG120. Misc. Topics

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

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

structs as arguments

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 Tue. Young W. Lim Day14 A Tue 1 / 15

File and Console I/O. CS449 Spring 2016

Computer Programming Unit v

File Handling. Reference:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Goals of this Lecture

C for C++ Programmers

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

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Fundamentals of Programming. Lecture 10 Hamed Rasifard

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

Course organization. Course introduction ( Week 1)

Transcription:

EXAMINATION REGULATIONS and REFERENCE MATERIAL for ENCM 339 Fall 2017 Section 01 Final Examination The following regulations are taken from the front cover of a University of Calgary examination answer booklet. They are all in effect for the ENCM 339 examination, except that you are to write your answers on the question paper, not in an answer booklet. STUDENT IDENTIFICATION Each candidate must sign the Seating List confirming presence at the examination. All candidates for final examinations are required to place their University of Calgary I.D. cards on their desks for the duration of the examination. (Students writing mid-term tests can also be asked to provide identity proof.) Students without an I.D. card who can produce an acceptable alternative I.D., e.g., one with a printed name and photograph, are allowed to write the examination. A student without acceptable I.D. will be required to complete an Identification Form. The form indicates that there is no guarantee that the examination paper will be graded if any discrepancies in identification are discovered after verification with the student s file. A Student who refuses to produce identification or who refuses to complete and sign the Identification Form is not permitted to write the examination. EXAMINATION RULES (1) Students late in arriving will not normally be admitted after one-half hour of the examination time has passed. (2) No candidate will be permitted to leave the examination room until one-half hour has elapsed after the opening of the examination, nor during the last 15 minutes of the examination. All candidates remaining during the last 15 minutes of the examination period must remain at their desks until their papers have been collected by an invigilator. (3) All inquiries and requests must be addressed to supervisors only. (4) Candidates are strictly cautioned against: (a) speaking to other candidates or communicating with them under any circumstances whatsoever; (b) bringing into the examination room any textbook, notebook or memoranda not authorized by the examiner; (c) making use of calculators and/or portable computing machines not authorized by the instructor; (d) leaving answer papers exposed to view; (e) attempting to read other student s examination papers. The penalty for violation of these rules is suspension or expulsion or such other penalty as may be determined. (5) Candidates are requested to write on both sides of the page, unless the examiner has asked that the left hand page be reserved for rough drafts or calculations. (6) Discarded matter is to be struck out and not removed by mutilation of the examination answer book. (7) Candidates are cautioned against writing in their answer book any matter extraneous to the actual answering of the question set. (8) The candidate is to write his/her name on each answer book as directed and is to number each book. (9) A candidate must report to a supervisor before leaving the examination room. (10) Answer books must be handed to the supervisor-in-charge promptly when the signal is given. Failure to comply with this regulation will be cause for rejection of an answer paper. (11) If during the course of an examination a student becomes ill or receives word of a domestic affliction, the student should report at once to the supervisor, hand in the unfinished paper and request that it be cancelled. If physical and/or emotional ill health is the cause, the student must report at once to a physical/counsellor so that subsequent application for a deferred examination is supported by a completed Physician/Counsellor Statement form. Students can consult professionals at University Health Services or University Counselling Services during normal working hours or consult their physician/counsellor in the community. Should a student write an examination, hand in the paper for marking, and later report extenuating circumstances to support a request for cancellation of the paper and for another examination, such a request will be denied. (12) Smoking during examinations is strictly prohibited. Reference material appears on the following pages...

ENCM 339 Fall 2017 Section 01: Reference Material for Final Examination page 2 of 6 Introduction Documentation for some C library facilities starts on this page and continues on page 3. Documentation and/or examples for some Python language features and library facilities can be found on pages 4 6. Documentation for some C library facilities int strcmp(const char *left, const char *right); Each argument must be a pointer to the beginning of a string. If the two strings match exactly, the return value is 0. If the string accessed via left is less than the string accessed via right, the return value is < 0. If the string accessed via left is greater than the string accessed via right, the return value is > 0. Examples, which assume that the character set in use is ASCII: strcmp("ab", "ab") would return 0. strcmp("ab", "ac") would return a value < 0. strcmp("aba", "ab") would return a value > 0. strcmp("ab", "Z") would return a value > 0, because uppercase letters have lesser ASCII code values than lowercase letters. void* malloc(size_t nbytes); size_t is a typedef for some unsigned integer type. nbytes must be greater than or equal to 1. malloc returns either a pointer to the beginning of a newly allocated block of nbytes bytes in the heap, or NULL to indicate that it could find no such block. The bytes in the allocated block are not initialized any particular value. void free(void *p); p must be either NULL or a pointer to the beginning of a block of bytes allocated using malloc. If p is NULL, free does nothing; otherwise free deallocates the block pointed to by p. FILE* fopen(const char *filename, const char *mode); filename and mode must point to the beginnings of strings. fopen tries to open the file named by filename in the mode specified by mode. Modes used in ENCM 339 include: "r" for reading from a text file and "rb" for reading from a binary file; "w" for writing to a text file, either creating a new file, or replacing the contents of an older file; "a" for writing to a text file, either creating a new file, or appending to the contents of an older file; "wb" and "ab", similar to "w" and "a", but for binary files. (There are many other possible modes.) If fopen succeeds it returns a pointer that can be used for further operations on the file; if fopen fails, it returns NULL. EOF EOF is a preprocessor macro defined as some negative integer constant. It is used by many (not all!) standard C library I/O functions as a return value to indicate an error, possibly end-of-file, and possibly some other kind of error. int fclose(file *stream); stream must be a file pointer corresponding to an open file. fclose breaks the connection between program and file. It returns EOF to indicate that errors were detected in closing the file, and 0 otherwise. int fgetc(file *stream); stream must be a file pointer corresponding to a text file open for input. fgetc normally reads the next character from stream and returns its character code. fgetc returns EOF to indicate end-of-file or error.

ENCM 339 Fall 2017 Section 01: Reference Material for Final Examination page 3 of 6 char* fgets(char *s, int size, FILE *stream); s must point to the beginning of an array that has at least size chars of storage, and stream must be a file pointer corresponding to a text file open for input. fgets will read characters from stream and copy them into the array until one of the following things has happened: a newline character has been read and copied into the array; size - 1 characters have been read and copied, with none of them being a newline; EOF was returned on an attempt to read a character in this case, EOF is not copied into the array. In each of the three cases, fgets will terminate the string in the array with a \0. The return value is s if at least one character was copied into the array, and NULL otherwise. int fscanf(file *stream, const char *format,...); stream must be a file pointer corresponding to a text file open for input. In this simple example... int i, j; i = fscanf(fp, "%d", &j);... i will get a value of 1 on success, 0 on failure because the wrong kinds of characters were in the input stream, and EOF on failure for some other reason. int fputc(int c, FILE *stream); stream must be a file pointer corresponding to a text file open for output. c must be a character code. fputc writes the character code to the output file. int fputs(const char *s, FILE *stream); stream must be a file pointer corresponding to a text file open for output. s must point to the beginning of a string. fputs writes all of the characters in the string, up to but not including the terminating \0, to the output file. int fprintf(file *stream, const char *format,...); stream must be a file pointer corresponding to a text file open for input. In this simple example... fprintf(fp, "hello %d", 100-1);... the character sequence hello 99 will be written to the output stream. size_t fread(void *p, size_t size, size_t count, FILE *stream); stream must be a file pointer corresponding to a binary file open for input. p must point to the beginning of a chunk of at least size*count bytes of memory. fread attempts to copy count items, each item size bytes in size, from the file to memory. The return value is the number of items actually copied from the file. size_t fwrite(const void *p, size_t size, size_t count, FILE *stream); stream must be a file pointer corresponding to a binary file open for output. p must point to the beginning of a chunk of at least size*count bytes of memory. fwrite attempts to copy count items, each item size bytes in size, from memory to the file. The return value is the number of items actually copied to the file. stdin, stdout and stderr stdin, stdout, and stderr can be thought of as constants of type FILE*. stdin is the standard input stream, accessed, for example, using scanf. stdout is the standard output stream, accessed, for example, using printf. stderr is another output stream, and is the preferred channel for error messages.

ENCM 339 Fall 2017 Section 01: Reference Material for Final Examination page 4 of 6 Python documentation and code examples A few important builtin functions len(container) number of items in a sequence, or number of key-value pairs in a dict object. print(arguments) print output. By default, print puts a space between each argument value and a newline at the end, but that can be changed with sep=string and/or end=string. Use file=fileobject to send output to a file instead of the terminal. input(string) get a line of text from interactive input, using string as a prompt. range(stop) integers from 0 up to but not including stop, with a step of 1. range(start, stop) integers from start up to but not including stop, with a step of 1. range(start, stop, step) integers from start up to but not including stop, with a step of step. isinstance(object, type) True if the type of object is either type or a class that inherits from type; otherwise, False. open(filename, mode) open a file. Modes presented in ENCM 339 in Fall 2017 were: r w a x open text file for input open text file for output, either creating a new file or replacing an existing one open text file for output, either creating a new file or adding text at the end of an existing one open text file for output, but only if the file does not already exist open raises an instance of an OSError exception if it fails to open the file. Examples of container creation a = [ ] b = [5, cde ] c = () d = 7, e = fgh, 2.25 f = { } g = {339: fun, 353: also fun } Growing and shrinking lists Examples copy/pasted from an interactive session: = [12, 35, 27, 19].append(34) [12, 35, 27, 19, 34].insert(2, 42) [12, 35, 42, 27, 19, 34] >>> del mylist[3] [12, 35, 42, 19, 34] >>> del mylist[1:4] [12, 34] Splitting and joining strings Examples copy/pasted from an interactive session: # empty list # list with two items # empty tuple # tuple with 1 item # tuple with 2 items # empty dict # dict with 2 int keys

ENCM 339 Fall 2017 Section 01: Reference Material for Final Examination page 5 of 6 >>> mystr = this that other = mystr.split() [ this, that, other ] >>> mynewstr = /.join(mylist) >>> mynewstr this/that/other Examples of slices expression type value (23, 16, 31)[0:-1] tuple (23, 16) ABCDEFGHIJ [1:9:2] str BDFH [52, 55, 63, 68][-1:0:-1] list [68, 63, 55] Some operations with dictionaries key in dict True if key is in dict, False if key is not in dict. dict[key] = value update a key-value pair if key is already in dict; otherwise add a new key-value pair. del dict[key] remove key-value pair from dict. A KeyError exception is raised if key is not in dict. variable = dict[key] give variable the value associated with key. A KeyError exception is raised if key is not in dict. variable = dict.get(key) give variable the value associated with key, or None if key is not in dict. # Loop over keys. for k in dict: statement(s) # Loop over values. for v in dict.values(): statement(s) # Loop over key-value pairs. for k, v in dict.items(): statement(s) Text file input example: one line at a time somefile.txt line one line two line three line four line five program with open( somefile.txt ) as f: for line in f: print(line, end = "") if line == line three\n : break output line one line two line three Text file input example: all the lines at once Assume that somefile.txt is as given above. program with open( somefile.txt ) as f: lines = f.readlines() print(lines) output [ line one\n, line two\n, line three\n, line four\n, line five\n ] Text file output examples Both programs write 1, 2, 4, 8, 16, and 32 to powers.txt, one number per line. with open( powers.txt, w ) as f: for i in range(6): f.write(str(2**i) + \n ) with open( powers.txt, w ) as f: for i in range(6): print(2**i, file=f)

ENCM 339 Fall 2017 Section 01: Reference Material for Final Examination page 6 of 6 Example code with class types class SmartDog: def init (self, bark_par, age_par=0): self.bark, self.age = bark_par, age_par def str (self): f = {}-year-old dog who says {} return f.format(self.age, self.bark) def say_n(self, n): if n <= 0: print( [whimper] ) else: for i in range(n): print(self.bark, end=" ") print() def say_age(self): self.say_n(self.age) class PlusDog(SmartDog): def add(self, j, k): self.say_n(j + k) class TimesDog(SmartDog): def multiply(self, j, k): self.say_n(j * k) class SmartestDog(PlusDog, TimesDog): pass lassie = SmartestDog( ruff, 4) lassie.say_age() print(lassie) lassie.add(2, 3) lassie.multiply(2, 3) output of program ruff ruff ruff ruff 4-year-old dog who says ruff ruff ruff ruff ruff ruff ruff ruff ruff ruff ruff ruff Example code with exception handling secret = 7 while True: try: guess = int(input( Guess my integer? )) if guess == secret: break print( Sorry,, guess, is incorrect. ) except ValueError: print("that wasn t an integer!") print(guess, is correct! ) Below is an example dialog with the above program. User input is shown in a slanted font. Guess my integer? hello That wasn t an integer! Guess my integer? 6 Sorry, 6 is incorrect. Guess my integer? 7 7 is correct!