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

Similar documents
CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

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

Review: Constants. Modules and Interfaces. Modules. Clients, Interfaces, Implementations. Client. Interface. Implementation

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

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

UNIX input and output

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

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.

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

CSE 333 SECTION 3. POSIX I/O Functions

File Handling. 21 July 2009 Programming and Data Structure 1

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

File IO and command line input CSE 2451

Lecture 8: Structs & File I/O

File I/O. Preprocessor Macros

Pointers and File Handling

211: Computer Architecture Summer 2016

CSCI 171 Chapter Outlines

CS3157: Advanced Programming. Outline

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

Lecture 03 Bits, Bytes and Data Types

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

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

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

Review Topics. Final Exam Review Slides

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

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

CSE 333 SECTION 3. POSIX I/O Functions

CSE 410: Systems Programming

ENG120. Misc. Topics

2009 S2 COMP File Operations

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

Introduction to Programming Systems

Lecture 7: file I/O, more Unix

Computational Methods of Scientific Programming Fall 2007

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

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

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)

Do not turn the page until 5:00.

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

Computer Programming Unit v

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

Programming in C. Part 1: Introduction

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.

Advanced C Programming and Introduction to Data Structures

Standard File Pointers

Programming & Data Structure

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

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

Layers in a UNIX System. Create a new process. Processes in UNIX. fildescriptors streams pipe(2) labinstructions

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

25.2 Opening and Closing a File

Section 3: File I/O, JSON, Generics. Meghan Cowan

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

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

C PROGRAMMING. Characters and Strings File Processing Exercise

1 The CTIE processor INTRODUCTION 1

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

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

Goals of this Lecture

Recitation 2/18/2012

C mini reference. 5 Binary numbers 12

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

ECE264 Spring 2014 Exam 2, March 11, 2014

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

Processes. Johan Montelius KTH

Friday, September 16, Lab Notes. Command line arguments More pre-processor options Programs: Finish Program 1, begin Program 2 due next week

Chapter 14 - Advanced C Topics

A process. the stack

C Programming Language

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

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

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

628 Lecture Notes Week 4

Input / Output Functions

C Basics And Concepts Input And Output

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

PRINCIPLES OF OPERATING SYSTEMS

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

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

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

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

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

CSC209 Review. Yeah! We made it!

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

CSE 303: Concepts and Tools for Software Development

PROGRAMMAZIONE I A.A. 2017/2018

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

Fundamentals of Programming. Lecture 10 Hamed Rasifard

C programming basics T3-1 -

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

Intermediate Programming, Spring 2017*

SWEN-250 Personal SE. Introduction to C

EL2310 Scientific Programming

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

CSE 333 Midterm Exam July 24, Name UW ID#

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

Transcription:

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

Announcements Homework 2 posted Homework 1 due in two weeks Typo on HW1 (definition of Fib. Sequence incorrect) Prof. Stavrou will give the lecture today An extra-credit quiz (20 pts, 30 minutes) No computational device allowed Hand-execute the code, list output

Overview: the Standard Library A language is: The grammar of the language (keywords, operators, expressions, etc.) The execution environment (e.g., an OS, JVM, CLR) A library of supporting functions Language design is library design. -- Bjarne Stroustrup Example: Java (very large object library and API) Hint: read the man pages for the C library functions!

What is a Library? A collection of functions with a common purpose The collection provides a well defined standard interface or API to the library s core purpose: I/O Math Graphics/GUI Crypto many others

Collections of Functions The set of function definitions provide a set of contracts Inform callers how to set up and use the arguments (parameters) and results The design of the library and contracts/api provide some hints as to semantics and implementation details (security related think back to Sergey Bratus s article on Hacker Curriculum)

Header Files Header files are C source files that hold the definition of functions and data structures Header files end in.h The C standard library is composed of many header files as well as their corresponding implementation (i.e.,.c ) files You know one already: stdio.h

Example: Standard I/O Basic C data types provide storage for data when it is in your program s memory space Collections of data: structs, arrays, unions (last lecture) What about feeding data into these variables and sending data to other programs or files on disk? Streams or collections of bytes Files

Basic Concepts of Unix Files No markup (contrast with NTFS files) Every byte is addressable Access is byte by byte (char by char) Can perform random access (cover this later) Treat a file as a stream or sequence of bytes Everything in Unix is a file (in one form or another) So file I/O is important in C programs and so is having a robust, standard way of manipulating data in files!

C Programs and Standard Files Every C program is given 3 files automatically Standard output (what you see on screen) Standard input (usually attached to keyboard device) Standard error (also usually on screen) But via the magic of Unix, can be easily redirected to or from other sources and sinks Shell redirection See dup system call

Naming Standard Files The header file <stdio.h> defines three handles to these objects (of type FILE, a struct) Stdin stdout stderr These are variable names you can use in any code that includes stdio.h

Interesting I/O Functions Char output: putchar(), getchar(), putc(), getc() String input/output: fprintf(), fscanf() File I/O: fopen() / fclose() fread() / fwrite() These are different from the OS system calls: open, close, read, write They operate on C library FILE objects rather than OSlevel file descriptors

The FILE Structure Abstraction A data type defined in stdio.h A struct named FILE A common data type for use with most of the C I/O library functions So library design involves designing and defining appropriate data structures as well as functions See page 176 in TCPL for the definition

Opening Files: Who Knows What? Key Idea: translate a file name to something the OS can manipulate The C library steps in the way Concept stack A filename: a character sequence humans understand A FILE object: something your program (via stdio.h) understands A file descriptor (an integer the OS uses to keep track of unique file handles)

Opening Files via stdio.h //consult man fopen for details! #include <stdio.h> //two arguments: file name and mode FILE* fin = fopen( /tmp/name, rb ); //now fin represents a valid FILE object, right? //wrong! need to test the result of fopen()! if(null==fin){ //an error occurred, handle it

Contract vs. Implementation fopen s contract is: Give me a valid file path and a mode (read, write, append, truncate, etc., see man page) AND I might return to you a valid pointer to a valid FILE object How does C library do all that? It doesn t do it all. It asks the OS for help.

Contract vs. Implementation 2 Many standard library functions employ a system call (some don t) to help accomplish the underlying task System calls define the OS s API A collection of services the OS will provide to application programs But can be tedious to use and set up So C library is a higher level of abstraction

Contract vs. Implementation 3 fopen employs the open() system call //see man 2 open int open(const char* pathname, int flags);

Other C Libraries

Character manipulation #include <ctype.h> isascii(int), islower(int), isupper(int), isdigit(int) tolower(int), toupper(int)

String Manipulation #include <string.h> Defines the symbol NULL Memory copy routines, the strlen() routine, string tokenization, some error output routines, more on those when we get to memory management

stdlib.h Collection of many utility functions exit, abort, atoi, atof, system() malloc, calloc, realloc, free (will talk about these in a later lecture, not now ) getenv, putenv, setenv rand, srand

errno.h Defines a list of standard error names (rather than keeping track of error numbers ) Defines the errno integer variable perror() from stdio.h is related (but in a different library) Get in the habit of testing errno s value!

math.h Defines common math symbols (pi, e, etc.) Defines values for representing limits of primitive types (INFINITY, NAN, etc.) Defines tan, cos, sin, exp, abs, floor, ceil, log, round, etc.

Create Your Own Library

Anyone Can Create a Library Just a collection of: Contract definitions Symbol and data type definitions Function implementations Components: Header files Library binary (or source) files

Note: Library Interception Linking is not done until runtime Can dynamically replace function implementations DLL Injection Library interposition Unix: LD_PRELOAD environment variable Affects search path for library function implementation

libmemtag.a Design a library that allows you to associate memory locations with arbitrary string tags Need: an API (data definitions and set of functions) a binary implementation

libmemtag header file (memtag.h) #ifndef MEMTAG_H_ #define MEMTAG_H_ typedef struct _memory_tag{ char* content; unsigned int length; } MTag ; int tagmem(void* addr, unsigned long long extent, MTag* tag); #endif

Implementation (memtag.c) #include memtag.h int tagmem(void* address, unsigned long long extent, MTag* tag) { if(null==tag NULL==tag->content) return -1; //more error checking, and associate memory address //with the tag in some internal data structure // return 0; }

Package the Library (Makefile) memtag.o: memtag.c memtag.h gcc Wall g c memtag.c libmemtag.a: memtag.o ar rc $@ memtag.o

Use the Library in your code (test.c) #include memtag.h int main(int argc, char* argv[]) { int myint = 100; MTag mtag; mtag.content = yellow ; mtag.length = strlen(mtag.content); tagmem(&myint, sizeof(myint), &mtag); return 0; }

Telling the Compiler about the Library LDFLAGS=-L../lib L/usr/lib INCLUDES=-I/usr/include I../include LIBS=-lmemtag test: test.c gcc $(LDFLAGS) $(INCLUDES) o test test.c $(LIBS)