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

Similar documents
CSC209H Lecture 3. Dan Zingaro. January 21, 2015

COMP1917: 09 Arrays and Strings

25.2 Opening and Closing a File

CSC 2405: Computer Systems II

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.

File IO and command line input CSE 2451

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

CSC Execution Environment. Program Execution Environment

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

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

COMP s1 Lecture 1

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

In the case of the dynamic array, the space must be deallocated when the program is finished with it. free(x);

CSE 333 Midterm Exam July 24, Name UW ID#

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

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430

C-Refresher: Session 10 Disk IO

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

Intermediate Programming, Spring 2017*

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

IO = Input & Output 2

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

Homework 2 Answers. Due Date: Monday, April 29, 2002, at 11:59PM Points: 100

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

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

EL2310 Scientific Programming

8. Characters, Strings and Files

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

Recitation 2/18/2012

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

CSE 374 Programming Concepts & Tools

2009 S2 COMP File Operations

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Organization of a file

C for C++ Programmers

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

CSE 333 Midterm Exam July 24, 2017 Sample Solution

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

Direct Memory Access. Lecture 2 Pointer Revision Command Line Arguments. What happens when we use pointers. Same again with pictures

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Problem Set 1: Unix Commands 1

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

CSE 333 Lecture 7 - final C details

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

Strings. Steven R. Bagley

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.

A programmer can create Internet application software without understanding the underlying network technology or communication protocols.

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

File I/O. Preprocessor Macros

Computer Science & Engineering 150A Problem Solving Using Computers

Input/Output and the Operating Systems

CSE 303: Concepts and Tools for Software Development

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

Programming in C. Pointers and Arrays

Object oriented programming C++

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

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

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4500/8506 Operating Systems Summer 2016 Programming Assignment 1 Introduction The purpose of this

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

EL2310 Scientific Programming

CS1003: Intro to CS, Summer 2008

Inter-Process Communication

C++ Lab 02 - Command Line Arguments and Strings

C mini reference. 5 Binary numbers 12

CS240: Programming in C

C PROGRAMMING. Characters and Strings File Processing Exercise

Today s Learning Objectives

PROGRAMMAZIONE I A.A. 2017/2018

Input / Output Functions

Warm-up sheet: Programming in C

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4500/8506 Operating Systems Fall Programming Assignment 1 (updated 9/16/2017)

CSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community

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

CP2 Revision. theme: file access and unix programs

Unix-Linux 2. Unix is supposed to leave room in the process table for a superuser process that could be used to kill errant processes.

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

COP4342 UNIX Tools Assignment #3: A Simple Unix Shell. Instructor: Dr. Robert Van Engelen Teaching Assistant: Imran Chowdhury Spring 2018

Chapter 8 C Characters and Strings

211: Computer Architecture Summer 2016

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Standard C Library Functions

CSE 303 Midterm Exam

Introduction. Lecture 5 Files and Streams FILE * FILE *

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

CSE 12 Spring 2016 Week One, Lecture Two

EL2310 Scientific Programming LAB2: C lab session. Patric Jensfelt, Andrzej Pronobis

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

File Descriptors and Piping

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Computer Programming. The greatest gift you can give another is the purity of your attention. Richard Moss

Lecture 5 Files and Streams

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

CSE 333 SECTION 3. POSIX I/O Functions

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

Standard File Pointers

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

Transcription:

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

Input/Output Most useful programs will provide some type of input or output Thus far, we ve prompted the user to enter their input directly scanf There are more options: Command line arguments File I/O 2/5/18 CS 220: Parallel Computing 2

Today s Agenda Command Line Arguments Reading and Processing Files Error Handling 2/5/18 CS 220: Parallel Computing 3

Today s Agenda Command Line Arguments Reading and Processing Files Error Handling 2/5/18 CS 220: Parallel Computing 4

Input From the Command Line Passing command line arguments is a common form of input:./my_program testmode./file.txt We see this often with Unix utilities: ls -l /my/directory This makes providing input to a program easier, and allows for scripting as well:./my_program ${MODE}./file.txt 2/5/18 CS 220: Parallel Computing 5

Command Line Arguments You may have noticed an alternative version of our main(void) function: int main(int argc, char *argv[]) This allows us to accept and process command line arguments For example, when you run git status, the string status is passed to the main method In fact, so is the name of the program, git 2/5/18 CS 220: Parallel Computing 6

Argument Attributes We receive two parameters: argc the number of command line arguments argv the arguments themselves Some notes: argc will always be at least 1 argv will always start with the name of your program a.out array So if we want one argument, status, we test whether argc == 2 2/5/18 CS 220: Parallel Computing 7

Looking Closer: argv Another thing to notice: how argv is defined char *argv[] A pointer to an array Which we know is also represented by a pointer Or in other words, a pointer to a pointer Here s another valid definition of argv: char **argv So this is a 2D array: an array of character arrays 2/5/18 CS 220: Parallel Computing 8

Processing Arguments Command line arguments are C strings They are terminated by \0 If we re looking for a status command, we can do a string comparison: strcmp(argv[1], "status"); If the string matches, we ll run the status functionality in our hypothetical git program 2/5/18 CS 220: Parallel Computing 9

strcmp char stra[] = "Hello"; char strb[] = "Hello World!"; if (strcmp(stra, strb) == 0) { } printf("they're the same!\n"); Why == 0? 2/5/18 CS 220: Parallel Computing 10

Converting Arguments In many cases, you ll want to accept an integer on the command line Converting a string to integer is accomplished with the atoi() function Available in the C standard library: #include <stdlib.h> There are some others: atof(), atol() You may also wonder if there is an itoa() function There is! But it is NOT part of the C standard 2/5/18 CS 220: Parallel Computing 11

Demo: Command Line Args 2/5/18 CS 220: Parallel Computing 12

Today s Agenda Command Line Arguments Reading and Processing Files Error Handling 2/5/18 CS 220: Parallel Computing 13

Opening a File /* This opens the file specified by the first command line argument: */ printf("opening file: %s\n", argv[1]); FILE *file = fopen(argv[1], "r"); /* Note the r : open for reading */ 2/5/18 CS 220: Parallel Computing 14

Open Modes The basics: r read w write a append This isn t the full story, however: each mode can be followed by a + r+ - open for read and write, file must exist w+ - open for read and write, file is created if not present There are more details in the man page for fopen() 2/5/18 CS 220: Parallel Computing 15

Reading Line by Line fgets Once we have opened a file, we need to read it A common approach is reading line by line via the fgets function: char line[500]; while (fgets(line, 500, file)!= NULL) { /* Process the line */ } This uses a 500-character buffer to store the line fgets will also stop once it finds a newline (\n) character 2/5/18 CS 220: Parallel Computing 16

Rewinding a File When you reach the end of a file, you ll get a NULL or EOF return value This tells you that you ve reached the End Of File If you want to loop through the file again, go back to the start: fseek(file, 0L, SEEK_SET); rewind(file); /* Note: old, deprecated */ You can also re-open the file 2/5/18 CS 220: Parallel Computing 17

Cleaning Up It s good practice to also close your files when you re done with them: fclose(file) Each file you open uses up a file descriptor The operating system imposes limits on how many file descriptors can be open per program When you open several files, don t forget to close them when you re done! 2/5/18 CS 220: Parallel Computing 18

String Tokenization A common use case for strings is tokenization Or, splitting them based on characters Consider the following string: "Hello, how are you today?"; How can we retrieve each word individually? [Hello,] [how] [are] [you] [today?] Java/Python have nice split() methods for this In C, we can use strtok 2/5/18 CS 220: Parallel Computing 19

Tokenizing a String /* Tokenize based on space and newline * characters: */ char *token = strtok(line, " \n"); while (token!= NULL) { } /* do something with token */ /* then grab the next token: */ token = strtok(null, " \n"); 2/5/18 CS 220: Parallel Computing 20

Why include \n? Blank lines won t contain any tokens You d expect strtok() to just return NULL immediately, but this is not the case If there are *no* tokens found, the entire string is returned Makes more sense if we take a look at how strtok() is implemented 2/5/18 CS 220: Parallel Computing 21

How strtok Works When it comes to C functions, strtok is one of the stranger ones First, we pass in the string we want to tokenize After that, we pass in NULL and it gives us the next token How does it even know what string to operate on? strtok maintains a global pointer to the start of the most recent token 2/5/18 CS 220: Parallel Computing 22

strtok Global State In C, we have global and local variables Globals are defined outside of any function For example, up above your main function Some C library functions even do this When you #include them, they get added to your code C provides the static keyword to restrict global variables scope to their compilation unit Generally compilation unit = file This way we don t pollute the global namespace 2/5/18 CS 220: Parallel Computing 23

strtok Splitting Strings Beyond the strange pointer magic, we also need to know how strtok splits things up It scans through the string until it comes across one of the user-defined tokens The token is replaced with \0 Now printing the string only prints up to the NUL byte To move to the next token, strtok simply changes the pointer to come after the NUL byte! 2/5/18 CS 220: Parallel Computing 24

Today s Agenda Command Line Arguments Reading and Processing Files Error Handling 2/5/18 CS 220: Parallel Computing 25

Error Handling Thus far we ve pretended that errors don t happen This can be okay: if a user doesn t enter a value, for instance, then maybe everything will just be zero Sometimes you do need to know when something went wrong Example: trying to read a file that doesn t exist In C, errors are indicated with the return code You need to check the function info to find out what the return codes mean 2/5/18 CS 220: Parallel Computing 26

Printing Error Messages The perror() function is your friend when you want to get a user-friendly description of what went wrong cannot access 'blah.txt': No such file or directory When an error occurs, the C library updates the last error code Calling perror() will look up this error code and print a friendly description You can add a prefix string to help you trace through your code 2/5/18 CS 220: Parallel Computing 27

Opening a File: Error Handling #include <stdlib.h> FILE *file = fopen("data.txt", "r"); if (file == NULL) { perror("fopen"); return EXIT_FAILURE; } 2/5/18 CS 220: Parallel Computing 28

Error handling perror() One important note about using the perror() function: it only knows about C library errors If you prompt the user to enter a positive number and they enter a negative one instead, perror() won t help In those cases, you re on your own But still make sure you report the error! 2/5/18 CS 220: Parallel Computing 29

EXIT_FAILURE You may have noticed EXIT_FAILURE in the previous example This indicates that your program had to stop because of some type of error condition All programs provide an exit code 0 generally means success 2/5/18 CS 220: Parallel Computing 30

Quitting in Style exit() function #include <stdlib.h> /* If you re not in main(), you can still quit your program: */ void my_func(void) { printf("hello?\n"); exit(exit_failure); } 2/5/18 CS 220: Parallel Computing 31