Exercise Session 3 Systems Programming and Computer Architecture

Size: px
Start display at page:

Download "Exercise Session 3 Systems Programming and Computer Architecture"

Transcription

1 Systems Group Department of Computer Science ETH Zürich Exercise Session 3 Systems Programming and Computer Architecture Herbstsemester 2016

2 Agenda Review of Exercise 2 More on C-Programming Outlook to Exercise 3 Quiz

3 Checking your Arguments Make sure that you check your arguments before using them. Especially pointers: void (*f)(int); f = null; callfptr(f, 123); int *data = null; reverse(data, -3); Is your code still valid with these invocation? Systems Programming and Computer Architecture 3

4 Initializing Memory It may not always be the case that your allocated memory is zeroed out: #include <string.h> int *data = malloc(10 * (sizeof(int))); if (data == null) { printf( No memory ); } // ensure memory is zeroed out memset(data, 0, 10 * sizeof(int))); Systems Programming and Computer Architecture 4

5 Choose Your Types Wisely When you define your interface to your function, always have in mind which values you want to accept void reverse_array(int array[], int length); void reverse_array(int array[], size_t length); Remember: The bit representation stays the same, but the interpretation of 0xFFFFFFFF may be different.. Systems Programming and Computer Architecture 5

6 Solution of Exercise 2

7 1. Reverse an array Write a C program that has a function that: accepts an array of 32-bit unsigned integers and a length reverses the elements of the array in place returns void (nothing)

8 Solution void ReverseArray(uint32_t *arr, unsigned int len) { int i; // check the obvious corner case of no reversal needed if (len <= 1) return; // make sure the caller passed us a valid array assert(arr!= NULL); // do the reversal // think through the termination condition carefully for (i=0; i<(len/2); i++) { uint32_t tmp; } } tmp = arr[i]; arr[i] = arr[len-i-1]; arr[len-i-1] = tmp;

9 4. Little vs. big endian Write a C program that prints out whether the computer it is running on is little endian or big endian. (hint: pointer arithmetic from the lecture)

10 Solution int main(int argc, char **argv) { int x = 1; char *charptr = (char *) &x; if (*charptr == 1) { printf("little endian\n"); } else { printf("big endian\n"); } } return 0;

11 C-Programming

12 Cleanup code with Goto struct person * alloc_person(){ struct person * ret = malloc(sizeof(struct person)); ret->first_name = malloc(100 * sizeof(char)); ret->last_name = malloc(100 * sizeof(char)); return ret; } malloc() can fail, returns NULL. Correct code must not leak memory.

13 Cleanup code with Goto Perform operation 1 If failure, goto exit 1 Perform operation 2 If failure, goto exit 2 Perform operation 3 If failure, goto exit 3 Return success Exit 3: Exit 2: Exit 1: Undo operation 3 Undo operation 2 Return an error Not easy to represent scalably in structured programming Best effort: nested if statements But can get arbitrarily deep in a complex function goto version is highly stylized (undos can be paired with operations in reverse order) Can also be modified to handle cases where one undo deals with several operations

14 Cleanup code with Goto struct person * alloc_person(){ struct person * ret = malloc(sizeof(struct person)); if(!ret) goto err_3; ret->first_name = malloc(100 * sizeof(char)); if(!ret->first_name) goto err_2; ret->last_name = malloc(100 * sizeof(char)); if(!ret->last_name) goto err_1; return ret; err_1: err_2: err_3: } free(ret->first_name); free(ret); return NULL;

15 File I/O File Descriptors, Read, Write Systems Programming and Computer Architecture 15

16 Files in Linux Pretty much everything is a file: Files on hard drive Network Sockets Pipes Std IO (stdin, stderr and stdout) Systems Programming and Computer Architecture 16

17 Accessing Files In general you cannot access the file directly You need support from the operating system to open/read/write/close a file. This is called a system call (syscall) -> Lecture Operating System & Network All file related stuff is in the stdio.h Systems Programming and Computer Architecture #include <stdio.h> 17

18 The File Descriptor To access a file you need some reference to it FILE *fp; Current offset in the file (cursor) File Descriptor Pointer to the file File FOO File BAR Systems Programming and Computer Architecture 18

19 The File Descriptor To get a file descriptor you have to open a file FILE *fopen(const char *filename, const char *mode); The opening may fail. Check return value! Close the file in the end int fclose(file *fp); Systems Programming and Computer Architecture 19

20 (Text) File Opening Modes Mode Read Write File Not Exists File Exists r Yes, from beginning w No Yes, from the beginning a No Yes, from the end (append) r+ Yes, from beginning w+ Yes, from beginning a+ Yes, from beginning Systems Programming and Computer Architecture No Error FILE* descriptor returned Yes, from beginning Yes, From beginning Yes, from the end (append only) New file created, FILE* Descriptor returned New file crated, FILE* descriptor returned Error.. b Binary flag that can be added for binary IO New file created, FILE* descriptor returned New file crated, FILE* descriptor returned FILE* descriptor returned FILE* descriptor returned FILE* descriptor returned. Delete file contents (overwrite), File* descriptor returned FILE* descriptor returned 20

21 Reading a Text File Reading a single char int fgetc(file *fp); Returns EOF on file end or error Reading one line in the text file of max count-1 length char *fgets(char *str, int count, FILE *fp); New line \n will terminate reading, \0 appended Direct file access size_t fread(void *buf, size_t size, size_t count, FILE *fp); Read (size * count) bytes from the file Returns the number of bytes read Systems Programming and Computer Architecture 21

22 Reading a Text File (Example) FILE *fp; int c; int n = 0; fp=fopen("myfile.txt","r"); if (fp ==NULL) { printf("error opening file"); } else { do { c = fgetc (fp); if (c == A') { n++; } } while (c!= EOF); fclose (fp); } printf( %i, n); What s this program doing? Can you do the same program using fread() or fgets()? What are the potential benefits / drawbacks? Systems Programming and Computer Architecture 22

23 Writing a Text File Writing a single char int fputc(int character, FILE *fp); Returns EOF on error, or the character written if success Reading one line in the text file of max count-1 length int *puts(char *str, FILE *fp); Copy contents of *str until \0 is reached. Returns non-negative vaue on success Direct file access size_t write(void *ptr, size_t size, size_t count, FILE *fp); Write (size * count) bytes from the file Returns the number of bytes written Systems Programming and Computer Architecture 23

24 Writing a Text File (Example) FILE *fp; char name]; printf( Enter your name: "); fgets (name, 256, stdin); What s this program doing? fp=fopen("myfile.txt", a"); if (fp ==NULL) { printf("error opening file"); } else { if ( fputs (name, fp) < 0) { printf("error writing file"); } fclose (fp); } Can you do the same program using fwrite() or fputc()? What are the potential benefits / drawbacks? Systems Programming and Computer Architecture 24

25 Always keep in mind All those function will change the state of the file descriptor by advancing the cursor position Sometimes not all data requested is read/written Keep track of how many bytes are processed Loop until finished Systems Programming and Computer Architecture 25

26 Navigating the Text File Getting the position of the cursor in the file Using an offset from the beginning long int ftell(file *fp); Reposition the file cursor Seeking: (offset = 0 or the return value of ftell) int fseek(file *fp, long int offset, int origin); Reset to the beginning void rewind(file *fp); Systems Programming and Computer Architecture 26

27 Formatting int fscanf(file *stream, const char *format,...); Dual of printf int a; char b[10]; fscanf(stdin, %d %s, &a, &b); Also sscanf may be useful Format string: %s Read string %d Read integer Systems Programming and Computer Architecture 27

28 Managing Files Create file FILE *fopen(const char *filename, const char *mode); Create directory Mode specifies the permission bits (R/W/X) int mkdir(const char *filename, const char *mode); Rename file / directory Returns 0 if successfully renamed int rename(const char *oldname, const char *newname); Deleting Returns 0 if successfully renamed int remove(const char *filename); Systems Programming and Computer Architecture 28

29 File IO: Resources Reference and Examples Read the man pages! man 3 getc man 3 isspace man 3 scanf Systems Programming and Computer Architecture 29

30 Heap The heap Large pool of unused memory, used for dynamically allocating data structures malloc() allocates chunks of memory in the heap, free() returns them malloc() maintains bookkeeping data in the heap to track allocated blocks. Address Space Kernel virtual memory User stack shared libraries Run-time heap Read/write segment (.data,.bss) Read-only segment (.init,.text,.rodata) Unused

31 Memory API // declared in stdlib.h typedef unsigned int size_t; void *malloc(size_t sz); // declared in stdlib.h void *calloc(size_t nm, size_t sz); // declared in stdlib.h void free(void *); // declared in stdlib.h void *realloc(void *ptr, size_t size);

32 structs struct typename { type name; type name; type name; }; struct list_el { unsigned long val; struct list_el *next; }; struct list_el my_list; Use "." to refer to fields in a struct p->x is nicer than (*p).x Use "->" to refer to fields through a pointer to a struct structs are passed by value

33 Struct tags and typedefs You can: typedef struct list_el el_t; Or even: Or even: typedef struct list_el { unsigned long val; struct list_el *next; } el_t; struct list_el my_list; el_t my_other_list; typedef struct list_el { unsigned long val; struct list_el *next; } list_el; struct list_el my_list; list_el my_other_list; Confusing. Better to stay with always using tags. Some projects (e.g. Linux kernel) prohibit typedefs of structs in their style guide Dynamic Memory Allocation AS

34 Outlook to Exercise 3

35 1. Implement a Complex number module consisting of the following source files: complex.c, complex.h includes a typedef to define a complex number a + bi, where a and b are doubles includes functions to: add, subtract, multiply, and divide complex numbers implement a test driver in test_complex.c, which contains main( ).

36 Recap: Complex Numbers Addition / Subtraction: (a + bi) ± (c + di) = (a ± c) + (b ± d)i Multiplication: (a + bi) (c + di) = (ac bd) + (ad + bc)i Division: a + bi c + di = (ac + bd) + (bc ad)i c 2 + d 2

37 Complex numbers create a struct complex_set (a set of complex numbers) implement alloc_set( ) and free_set( ): alloc_set( ) needs to use malloc twice: once to allocate a new complex_set, and once to allocate the points field inside it free_set( ) needs to use free twice

38 3. word-count (wc) wc = word count. Linux utility to count lines, words and characters. Not related to toilet. you can use template wc.c and only fill in the missing part Exercise is about reading c-code and understand it (because you do not have to implement much Use the function getc(fp) to retrieve the next character in a file

39 4. File I/O Read a text-file, parse it and write a simple report better do this on Linux (in Linux new lines are \n while on windows they are \r\n) you only have to have a look at lines where the first column starts with «25»

40 5. Function pointer In this problem, we will use and create function that utilizes function pointers. The file callback.c contains an array of records consisting of a fictitious class of celebrities. Each record consists of the first name, last name and age of the student. fill in the gaps you will write functions, use function pointers and do some other cool stuff nothing new, but quite a bit of work

41 Quiz Questions on handout.

42 Quiz 1: Pointer and Strings char *c[] = { ENTER, NEW, POINT, FIRST }; char **cp[] = { c+3, c+2, c+1, c }; char ***cpp = cp; main() { printf( %s, **++cpp); printf( %s, *--*++cpp+3); printf( %s, *cpp[-2]+3); printf( %s\n, cpp[-1][-1]+1); } Operator Precedence: (),[],., ->, expr++, expr-- (left-to-right) then *, &, ++expr, --expr (right-to-left) then + - * / & >> << ==!=

43 printf( %s, *++cpp); ++cpp *(++cpp) *(*(++cpp)) => POINT cpp cp cp E N P F N E O I T W I R E 0 N S R T T 0 0 0

44 printf( %s, *--*++cpp+3); *(++cpp) --(*(++cpp)) *(--(*(++cpp)))+3 => ENTER cpp cp cp E N P F N E O I T W I R E 0 N S R T T 0 0 0

45 printf( %s, *cpp[-2]+3); cpp[-2] *(cpp[-2]) (*(cpp[-2]))+3 => FIRST cpp cp cp E N P F N E O I T W I R E 0 N S R T T 0 0 0

46 printf( %s\n, cpp[-1][-1]+1); (cpp[-1]) (cpp[-1])[-1] ((cpp[-1])[-1])+1 => NEW cpp cp cp E N P F N E O I T W I R E 0 N S R T T 0 0 0

47 Quiz 1: Pointer and Strings printf( %s, **++cpp); (*(*(++cpp))) => POINT printf( %s, *--*++cpp+3); *(--(*(++cpp)))+3 => ENTER printf( %s, *cpp[-2]+3); (*(cpp[-2]))+3 => FIRST printf( %s\n, cpp[-1][-1]+1); ((cpp[-1])[-1])+1 => NEW POINTER STEW

48 Quiz 2: Memory API main() { int* ip = malloc(sizeof(int)); printf( %d\n, *ip); int* ip2 = calloc(1, sizeof(int)); printf( %d\n, *ip2); } free(ip); free(ip2);

49 Quiz 2: Memory API int* ip = malloc(sizeof(int)); printf( %d\n, *ip); Memory region returned by malloc not guaranteed to be zeroed (can print any value). If not enough memory will return NULL, possible NULL pointer dereference! int* ip2 = calloc(1, sizeof(int)); printf( %d\n, *ip2); Prints 0, calloc memory is guaranteed to be zeroed If not enough memory will return NULL, possible NULL pointer dereference! free(ip); free(ip2); If ip or ip2 is NULL no operation is performed (no check required for free).

50 Quiz 3: Structures #define PRINT(fmt, val) printf(#val = % #fmt \t, (val)) #define PRINT2(fmt, v1, v2) PRINT(fmt, v1); PRINT(fmt, v2); static struct S1 { char c[3], *s; } s1 = { abc, def }; static struct S2 { char *cp; struct S1 ss1; } s2 = { ghi, { jkl, mno } }; PRINT2(c, s1.c[0], *s1.s); PRINT2(s, s2.cp, s2.ss1.s); PRINT2(s, ++s2.cp, ++s2.ssl.s); (),[],., ->, expr++, expr-- (left-to-right) then *, &, ++expr, --expr (right-to-left) then + - * / & >> << ==!=

51 Quiz 3: Structures PRINT2(c, s1.c[0], *s1.s); s1.c[0] = a *s1.s = d PRINT2(s, s2.cp, s2.ss1.s); s2.cp = ghi s2.ssl.s = mno PRINT2(s, ++s2.cp, ++s2.ssl.s); ++s2.cp = hi ++s2.ssl.s = no

52 Obligatory XKCD

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

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data

More information

Systems Programming and Computer Architecture ( )

Systems Programming and Computer Architecture ( ) Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture (252-0061-00) Timothy Roscoe Herbstsemester 2016 AS 2016 Dynamic Memory Allocation 1 5: Dynamic memory

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

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

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch. 1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions

More information

File IO and command line input CSE 2451

File IO and command line input CSE 2451 File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to

More information

Input/Output and the Operating Systems

Input/Output and the Operating Systems Input/Output and the Operating Systems Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 I/O Functions Formatted I/O printf( ) and scanf( ) fprintf( ) and fscanf( ) sprintf( ) and sscanf( ) int printf(const char*

More information

File I/O. Preprocessor Macros

File I/O. Preprocessor Macros Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically

More information

C-Refresher: Session 10 Disk IO

C-Refresher: Session 10 Disk IO C-Refresher: Session 10 Disk IO Arif Butt Summer 2017 I am Thankful to my student Muhammad Zubair bcsf14m029@pucit.edu.pk for preparation of these slides in accordance with my video lectures at http://www.arifbutt.me/category/c-behind-the-curtain/

More information

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

System Programming. Standard Input/Output Library (Cont d) Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Binary I/O 2 3 4 5 Binary

More information

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

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments 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

More information

Question 1: Complex numbers

Question 1: Complex numbers Fall Term 2016 SYSTEMS PROGRAMMING AND COMPUTER ARCHITECTURE Assignment 3: More C [1] Assigned on: 6th Oct 2016 Due by: 13th Oct 2016 This assignment contains more C programming. Skeletons and source files

More information

UNIX System Programming

UNIX System Programming File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,

More information

Exercise Session 2 Systems Programming and Computer Architecture

Exercise Session 2 Systems Programming and Computer Architecture Systems Group Department of Computer Science ETH Zürich Exercise Session 2 Systems Programming and Computer Architecture Herbstsemester 216 Agenda Linux vs. Windows Working with SVN Exercise 1: bitcount()

More information

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

This code has a bug that allows a hacker to take control of its execution and run evilfunc(). Malicious Code Insertion Example This code has a bug that allows a hacker to take control of its execution and run evilfunc(). #include // obviously it is compiler dependent // but on my system

More information

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

File (1A) Young Won Lim 11/25/16 File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version

More information

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

Standard I/O in C, Computer System and programming in C Standard I/O in C, Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information 7. Environment

More information

System Software Experiment 1 Lecture 7

System Software Experiment 1 Lecture 7 System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized

More information

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

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty. ECE 264 Exam 2 6:30-7:30PM, March 9, 2011 I certify that I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise you will receive a 1-point penalty.

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

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

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline. CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random

More information

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

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

Pointers and File Handling

Pointers and File Handling 1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY

More information

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

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre Programming in C Session 8 Seema Sirpal Delhi University Computer Centre File I/O & Command Line Arguments An important part of any program is the ability to communicate with the world external to it.

More information

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

Systems Programming. 08. Standard I/O Library. Alexander Holupirek Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:

More information

Lecture 8 Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight Exercise 7 due Monday (out later today) POSIX Portable Operating System Interface Family of standards specified by the

More information

M.CS201 Programming language

M.CS201 Programming language Power Engineering School M.CS201 Programming language Lecture 16 Lecturer: Prof. Dr. T.Uranchimeg Agenda Opening a File Errors with open files Writing and Reading File Data Formatted File Input Direct

More information

Naked C Lecture 6. File Operations and System Calls

Naked C Lecture 6. File Operations and System Calls Naked C Lecture 6 File Operations and System Calls 20 August 2012 Libc and Linking Libc is the standard C library Provides most of the basic functionality that we've been using String functions, fork,

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection 1 Files 1.1 File functions Opening Files : The function fopen opens a file and returns a FILE pointer. FILE *fopen( const char * filename, const char * mode ); The allowed modes for fopen are as follows

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

CSE 410: Systems Programming

CSE 410: Systems Programming CSE 410: Systems Programming Input and Output Ethan Blanton Department of Computer Science and Engineering University at Buffalo I/O Kernel Services We have seen some text I/O using the C Standard Library.

More information

Systems Programming and Computer Architecture ( )

Systems Programming and Computer Architecture ( ) Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture (252-0061-00) Timothy Roscoe Herbstsemester 2016 1 4: Pointers Computer Architecture and Systems Programming

More information

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

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 8 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary October 2017 ENCM 339 Fall 2017 Section 01 Slide

More information

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

CS 261 Fall Mike Lam, Professor. Structs and I/O CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful

More information

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

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Programming in C. 4. Misc. Library Features, Gotchas, Hints and Tips. Dr. Neel Krishnaswami University of Cambridge

Programming in C. 4. Misc. Library Features, Gotchas, Hints and Tips. Dr. Neel Krishnaswami University of Cambridge Programming in C 4. Misc. Library Features, Gotchas, Hints and Tips Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair Beresford

More information

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

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C Outline Review HW1 (+command line arguments) Memory Layout File I/O HW1 REVIEW HW1 Common Problems Taking input from stdin (via scanf) Performing

More information

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS A mini Quiz 2 Consider the following struct definition struct name{ int a; float b; }; Then somewhere in main() struct name *ptr,p; ptr=&p;

More information

File and Console I/O. CS449 Spring 2016

File and Console I/O. CS449 Spring 2016 File and Console I/O CS449 Spring 2016 What is a Unix(or Linux) File? File: a resource for storing information [sic] based on some kind of durable storage (Wikipedia) Wider sense: In Unix, everything is

More information

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

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments 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

More information

File Handling. Reference:

File Handling. Reference: File Handling Reference: http://www.tutorialspoint.com/c_standard_library/ Array argument return int * getrandom( ) static int r[10]; int i; /* set the seed */ srand( (unsigned)time( NULL ) ); for ( i

More information

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

CSI 402 Lecture 2 Working with Files (Text and Binary) CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value

More information

ECE551 Midterm Version 2

ECE551 Midterm Version 2 Name: ECE551 Midterm Version 2 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

CP2 Revision. theme: file access and unix programs

CP2 Revision. theme: file access and unix programs CP2 Revision theme: file access and unix programs file access in C basic access functionality: FILE *fopen(const char *filename, const char *mode); This function returns a pointer to a file stream (or

More information

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

Memory Management. CSC215 Lecture

Memory Management. CSC215 Lecture Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time

More information

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

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060 CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than

More information

Computer programming

Computer programming Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci T.U. Cluj-Napoca - Computer

More information

HIGH LEVEL FILE PROCESSING

HIGH LEVEL FILE PROCESSING HIGH LEVEL FILE PROCESSING 1. Overview The learning objectives of this lab session are: To understand the functions used for file processing at a higher level. o These functions use special structures

More information

PRINCIPLES OF OPERATING SYSTEMS

PRINCIPLES OF OPERATING SYSTEMS PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)

More information

Exercise Session 2 Simon Gerber

Exercise Session 2 Simon Gerber Exercise Session 2 Simon Gerber CASP 2014 Exercise 2: Binary search tree Implement and test a binary search tree in C: Implement key insert() and lookup() functions Implement as C module: bst.c, bst.h

More information

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

fopen() fclose() fgetc() fputc() fread() fwrite() The ability to read data from and write data to files is the primary means of storing persistent data, data that does not disappear when your program stops running. The abstraction of files that C provides

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Seven: Strings and Files Name: First Name: Tutor: Matriculation-Number: Group-Number:

More information

Processes. Johan Montelius KTH

Processes. Johan Montelius KTH Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other

More information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 15: Unix interface: low-level interface Cristina Nita-Rotaru Lecture 15/Fall 2013 1 Streams Recap Higher-level interface, layered on top of the primitive file descriptor

More information

Data File and File Handling

Data File and File Handling Types of Disk Files Data File and File Handling Text streams are associated with text-mode files. Text-mode files consist of a sequence of lines. Each line contains zero or more characters and ends with

More information

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

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing Chapter 14: File Processing Files and Streams C views each file simply as a sequential stream of bytes. It ends as if there is an end-of-file marker. The data structure FILE, defined in stdio.h, stores

More information

A process. the stack

A process. the stack A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes

More information

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

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430 Week 2 Intro to the Shell with Fork, Exec, Wait Sarah Diesburg Operating Systems CS 3430 1 Why is the Shell Important? Shells provide us with a way to interact with the core system Executes programs on

More information

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

File I/O. Arash Rafiey. November 7, 2017 November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files

More information

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

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

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

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc. Compound Statements So far, we ve mentioned statements or expressions, often we want to perform several in an selection or repetition. In those cases we group statements with braces: i.e. statement; statement;

More information

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12 BIL 104E Introduction to Scientific and Engineering Computing Lecture 12 Files v.s. Streams In C, a file can refer to a disk file, a terminal, a printer, or a tape drive. In other words, a file represents

More information

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

CMPS 105 Systems Programming. Prof. Darrell Long E2.371 + CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 7: The Environment of a UNIX process + Introduction + The main() fuction n int main(int argc, char* argv[]); n argc =

More information

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.

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. Name: ECE551 Midterm NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual work. You

More information

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

UNIT IV-2. The I/O library functions can be classified into two broad categories: UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

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

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based Chapter 5, Standard I/O Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based #include FILE *f; Standard files (FILE *varname) variable: stdin File Number: STDIN_FILENO

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

ENG120. Misc. Topics

ENG120. Misc. Topics ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File

More information

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

File Access. FILE * fopen(const char *name, const char * mode); File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header

More information

structs as arguments

structs as arguments Structs A collection of related data items struct record { char name[maxname]; int count; ; /* The semicolon is important! It terminates the declaration. */ struct record rec1; /*allocates space for the

More information

Goals of this Lecture

Goals of this Lecture I/O Management 1 Goals of this Lecture Help you to learn about: The Unix stream concept Standard C I/O functions Unix system-level functions for I/O How the standard C I/O functions use the Unix system-level

More information

CSE 333 Lecture 4 - malloc, free, struct, typedef

CSE 333 Lecture 4 - malloc, free, struct, typedef CSE 333 Lecture 4 - malloc, free, struct, typedef Administrivia HW1 is due on Friday, January 25th, 11:15am - see course overview web page for the late policy Be sure to check out the course discussion

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Heap Arrays. Steven R. Bagley

Heap Arrays. Steven R. Bagley Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files

More information

o Code, executable, and process o Main memory vs. virtual memory

o Code, executable, and process o Main memory vs. virtual memory Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,

More information

ECE551 Midterm Version 1

ECE551 Midterm Version 1 Name: ECE551 Midterm Version 1 NetID: There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly. This exam must be individual

More information

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

Lecture 04 Introduction to pointers

Lecture 04 Introduction to pointers Lecture 04 Introduction to pointers A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct access to a memory location through its address. A variable

More information

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture! I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix

More information

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture! I/O Management! 1 Goals of this Lecture! Help you to learn about:" The Unix stream concept" Standard C I/O functions" Unix system-level functions for I/O" How the standard C I/O functions use the Unix

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight HW2 Due Thursday, July 19 th Midterm on Monday, July 23 th 10:50-11:50 in TBD (And regular exercises in between) POSIX

More information

2009 S2 COMP File Operations

2009 S2 COMP File Operations 2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations

More information

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved. CS 33 Intro to Storage Allocation CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved. A Queue head typedef struct list_element { int value; struct list_element

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

Process Management! Goals of this Lecture!

Process Management! Goals of this Lecture! Process Management! 1 Goals of this Lecture! Help you learn about:" Creating new processes" Programmatically redirecting stdin, stdout, and stderr" Unix system-level functions for I/O" The Unix stream

More information

Computer Programming Unit v

Computer Programming Unit v READING AND WRITING CHARACTERS We can read and write a character on screen using printf() and scanf() function but this is not applicable in all situations. In C programming language some function are

More information

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

Contents. A Review of C language. Visual C Visual C++ 6.0 A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source

More information

CS1003: Intro to CS, Summer 2008

CS1003: Intro to CS, Summer 2008 CS1003: Intro to CS, Summer 2008 Lab #07 Instructor: Arezu Moghadam arezu@cs.columbia.edu 6/25/2008 Recap Pointers Structures 1 Pointer Arithmetic (exercise) What do the following return? given > char

More information

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Fundamentals of Programming. Lecture 10 Hamed Rasifard Fundamentals of Programming Lecture 10 Hamed Rasifard 1 Outline File Input/Output 2 Streams and Files The C I/O system supplies a consistent interface to the programmer independent of the actual device

More information