CAAM 420 Notes Chapter 2: The C Programming Language
|
|
- Crystal Gilmore
- 6 years ago
- Views:
Transcription
1 CAAM 420 Notes Chapter 2: The C Programming Language W. Symes and T. Warburton October 2, Stack Overflow Just for warmup, here is a remarkable memory bust: 1 / Author : WWS 3 Purpose : i l l u s t r a t e s t a c k o v e r f l o w most systems have 5 s t r i c t l i m i t to the s i z e o f the stack, which i n c l u d e s the region in which automatic v a r i a b l e memory 7 r e s i d e s. / 9 // l e n g t h o f a r e a l l y long array 11 #define N // comment t h i s out to see s t a c k o v e r f l o w 13 //#d e f i n e DYN 15 #include <s t d i o. h> #ifdef DYN 17 #include <s t d l i b. h> #endif 19 int main ( ) { 21 int i ; 23 // the s c a n f pause t r i c k s c a n f ( %d,& i ) ; 25 // dynamic a l l o c a t i o n #ifdef DYN double x = ( double ) malloc (N sizeof ( double ) ) ; 29 #else // vs s t a t i c a l l o c a t i o n o f t he same workspace 31 double x [N ] ; #endif 33 // now t r y to a c c e s s for ( i =0; i<n; i ++) x [ i ] = 0. 0 ; 35 1
2 it s called a stack overflow. The stack - the part of machine memory where program code resides, along with a data region for automatic memory - has a limited size. The system utility ulimit, run on my MacBook Pro, shows $ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) 6144 file size (blocks, -f) unlimited max locked memory (kbytes, -l) unlimited max memory size (kbytes, -m) unlimited open files (-n) 256 pipe size (512 bytes, -p) 1 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 266 virtual memory (kbytes, -v) unlimited (generally if you use tcsh, limit will do the same thing as ulimit -a under bash - see this web site for info). Thus much more than 8 MB of data allocated is likely to cause trouble. As it turns out, to cause real mayhem you need to allocate more than that x 8 =12.8 MB - but that does it. Notice that not even the first instruction gets executed - the command cannot even load! 23 File I/O Up to this point, the only method I ve shown you for moving data into our out of files is via input or output redirection. That s not an adequate toolset for many scientific programming tasks in which file data must be manipulated during runtime. K&R cover this topic in section 7.5. The structural model underlying file i/o is that of a linear memory segment: a file is treated as an array of bytes, with the offset (distance in bytes) from various positions within the file (begin, end, current) measuring position of a byte within the file. The critical steps in file i/o, and the functions that perform them, are: fopen: fseek, ftell: fscanf, fprintf: fread, fwrite: fflush, fclose: opening the file - making it accessible to the process changing, reporting position (of the next byte to be read/written) within the file read, write ascii data read, write binary data ensure that data is physically on the disk or other media, detach the file from the running process Before describing the basic i/o facilities, I should mention that these functions (all names begin with f ) form the standard i/o library. Some of them are described in Ch. 7 of K&R, several are not. They are by far the most useful i/o functions in C. Another, low-level i/o library exists, with some of the same basic functionality and function names without the f prefix - this other library is described in section 8.2. For various reasons I won t go into, the standard libary is usually preferable. The standard i/o functions may be used in a lot of different ways, which are hard to remember - so it s nice that the man page on fopen lays them out clearly: if you forget, just enter man fopen, for example. A few remarks: 1. fopen: the return value of this function is a pointer to a special kind of structure (later this week!) called a file pointer (older terminology) or stream (newer, C++-motivated terminology), of type FILE *. Note: there is never any need to deal with FILE objects directly - only through pointers to them. Every other library function will use the FILE * value returned by fopen. If fopen fails (to make the file available, or to open it), it returns the zero pointer, which has the macro definition NULL and can be tested as a boolean. 2
3 fopen requires two arguments: (1) the file name (a string) and (2) a permission string, which may be one of r, r+, w, w+, and a couple of other not-so-useful options. r : non-destructive, opens file for reading only and places stream (file pointer) at beginning - start at the beginning. If the file doesn t exist, this option fails (returns a NULL pointer). Use this option to read (only) a file that should exist. r+ : non-destructive, opens file for reading and writing and places stream at beginning. Also fails if file does not exist. Use this option to access a existing file that you may also want to alter (write). w : destructive, truncates the file (i.e. trashes its contents) if it exists, creates it if it does not, positions stream at start. Use this option to create a new file or overwrite an existing one; for output only. w+ : destructive, truncates the file if it exists, creates it if it does not, positions stream at start, permits both reads and writes. Use this option to create a new file or overwrite an existing one, when you may also need to read from it after having written to it. 2. fseek, ftell: fseek has three args: a file pointer, a long integer offset, and a base position. Three base positions are macro-ized, and are almost always the appropriate ones (usually the first): (1) begin-offile = SEEK SET, (2) end-of-file = SEEK END, and (3) current position = SEEK END. It returns 0 on success. ftell takes one argument, the file pointer, and returns the offset (in bytes, of coures, as an int). 3. fscanf, fprintf: well-described in K&R. Same as scanf and printf except that they read/write from/to an open file, and take the FILE * returned by fopen as first argument. 4. fread, fwrite: binary (i.e. non-human-readable) i/o. The great advantages of binary i/o are: (1) it s faster per unit information, because less translation is required, and (2) the files are smaller. Used to read into arrays: if T * x is initialized as an array of type T, either automatically or via a call to malloc, with length at least n, and fp is a FILE * returned from fopen with appropriate permssions, then nr=fread(x,sizeof(t),n,fp); attempts to read enough bytes for n words of type T into x, and reports that it actually succeeded in reading nr words. Similarly. nr=fwrite(x,sizeof(t),n,fp); attempts to write n words of type T from x into the file attached to FILE * fp. If nr is less than n on return, something went wrong. On return from either of these functions, the stream position (fp) is whereever the next byte to be read/written is located. So you can fill a file up by writing a loop over calls to fwrite, or read it from start to finish by looping over fread, assuming that the natural size of array to read is likely to be less than the file size. 5. fflush, fclose: fclose(fp) undoes what fp=fopen(...) did - the file is no longer associated with the file pointer fp. Because standard i/o is bufferred not written word-by-word to disk, but stored somewhere until the OS finds it convenient to access the disk controller - it s sometimes necessary to flush the buffers, and that s what fflush does. For example, if you are writing error messages and want to make sure you see them even if the program crashes, follow fprintf(fp,...) with fflush(fp). A rewrite of our previous example to write the same output, but to a file called hist.dat, illustrates some of these points: 3
4 1 #include <s t d l i b. h> #include <s t d i o. h> 3 #include <math. h> 5 int main ( int argc, char argv ) { 7 i f ( ( argc!=4)&&( argc!=5)) { p r i n t f ( Histogram g e n e r a t o r for sample mean o f C std l i b r a r y f u n c t i o n \n ) ; 9 p r i n t f ( random ( ), s c a l e d to produce pseudorandom numbers in the range \n ) ; p r i n t f ( [ 1, 1 ]. Computes mean over a sample o f p r e s c r i b e d s i z e, and\n ) ; 11 p r i n t f ( samples the r e s u l t i n g d i s t r i b u t i o n o f the mean over a p r e s c r i b e d \n ) ; p r i n t f ( number o f t r i a l s. Means s c a l e d by square r o o t o f number o f t r i a l s, \ n ) ; 13 p r i n t f ( so that l i m i t o f i n f i n i t e l y many t r i a l s i s Gaussian (CLT). \n ) ; p r i n t f ( Counts means in each o f a p r e s c r i b e d number o f equal s i z e d b i n s \n ) ; 15 p r i n t f ( ( s u b i n t e r v a l s o f [ 1, 1 ] ). Executes t h i s procedure a p r e s c r i b e d number\n ) ; p r i n t f ( o f times [ default =1], and p r i n t s the r e s u l t i n g histogram r e a l i z a t i o n s \n ) ; 17 p r i n t f ( to the f i l e \ h i s t. dat \ in the form o f x y p a i r s, x being bin c e n t e r and y being \n p r i n t f ( r e l a t i v e bin count, one p a i r to a l i n e, with two blank l i n e s \n ) ; 19 p r i n t f ( between s u c c e s s i v e r e a l i z a t i o n s. \ n\n ) ; p r i n t f ( usage : [ prog name ] [ sample s i z e ] [ number o f t r i a l s ] [ number o f histogram b i n s ] [ o p t i o 21 e x i t ( 1 ) ; 23 / 25 D e c l a r a t i o n s / 27 i n t nsamp ; // s i z e o f each sample i n t n t r i a l ; // number o f samples to g e n e r a t e 29 i n t nbin ; // number o f b i n s i n histogram i n t n r e a l ; // number o f r e a l i z a t i o n s 31 i n t i t r i a l ; // sample counter i n t isamp ; // in sample counter 33 i n t i b i n ; // bin counter i n t i r e a l ; // r e a l i z a t i o n counter 35 f l o a t mean ; // array o f n t r i a l means f l o a t h i s t ; // array o f nbin counts 37 f l o a t l b i n ; // workspace f o r l e f t endpoint o f bin f l o a t dbin ; // bin width 39 f l o a t rmax ; // max output o f random (2ˆ31 1), as f l o a t f l o a t s c a l e ; // s c a l e f a c t o r to approximate c e n t r a l tendency 41 FILE fp ; // output stream 43 / 45 / Statements 47 // s e t random seed by p r o c e s s number srandom ( g e t p i d ( ) ) ; 49 // compute max output o f random = 2ˆ31 1 ( clunky! ) 51 rmax=1; f o r ( i b i n =0; i b i n <31; i b i n++) rmax =2.0 f ; 53 rmax =1.0 f ; 55 // convert i n t p u t s to i n t e g e r s nsamp=a t o i ( argv [ 1 ] ) ; 57 n t r i a l=a t o i ( argv [ 2 ] ) ; 4
5 59 nbin=a t o i ( argv [ 3 ] ) ; // d e f a u l t 61 n r e a l =1; i f ( argc==5) n r e a l=a t o i ( argv [ 4 ] ) ; 63 // s a n i t y t e s t s 65 i f ( nsamp<0) { p r i n t f ( Error : sample N f o r each mean must be > 0, was %d\n, nsamp ) ; 67 e x i t ( 1 ) ; 69 i f ( n t r i a l <0) { p r i n t f ( Error : number o f means must be > 0, was %d\n, n t r i a l ) ; 71 e x i t ( 1 ) ; 73 i f ( nbin <0) { p r i n t f ( Error : number o f b i n s must be > 0, was %d\n, nbin ) ; 75 e x i t ( 1 ) ; 77 i f ( nreal <0) { p r i n t f ( Error : number histogram r e a l i z a t i o n s must be > 0, was %d\n, n r e a l ) ; 79 e x i t ( 1 ) ; 81 // s e t bin l e f t endpoint, width 83 l b i n = 1.0 f ; dbin =2.0 f / ( ( f l o a t ) nbin ) ; 85 // a l l o c a t e workspace f o r histogram, sample mean v e c t o r s 87 h i s t = ( f l o a t ) malloc ( nbin s i z e o f ( f l o a t ) ) ; i f (! h i s t ) { 89 p r i n t f ( Error : f a i l e d to a l l o c a t e memory f o r histogram \n ) ; e x i t ( 1 ) ; 91 mean = ( f l o a t ) malloc ( n t r i a l s i z e o f ( f l o a t ) ) ; 93 i f (! mean) { p r i n t f ( Error : f a i l e d to a l l o c a t e memory f o r means\n ) ; 95 e x i t ( 1 ) ; 97 // open f i l e 99 i f (! ( fp=fopen ( h i s t. dat, w ) ) ) { p r i n t f ( Error : f a i l e d to open output f i l e \ h i s t. dat \ \n ) ; 101 e x i t ( 1 ) ; 103 / 105 r e a l i z a t i o n loop / f o r ( i r e a l =0; i r e a l <n r e a l ; i r e a l ++) { // i n i t i a l i z e means, histogram 111 f o r ( i b i n =0; i b i n <nbin ; i b i n++) h i s t [ i b i n ]=0.0 f ; f o r ( i t r i a l =0; i t r i a l <n t r i a l ; i t r i a l ++) mean [ i t r i a l ]=0.0 f ; 113 // g e n e r a t e sample o f n t r i a l sums o f nsamp random nos. 115 f o r ( i t r i a l =0; i t r i a l <n t r i a l ; i t r i a l ++) 5
6 f o r ( isamp =0; isamp<nsamp ; isamp++) 117 mean [ i t r i a l ]+=2.0 f ( ( f l o a t ) ( random ( ) ) / rmax) 1.0 f ; 119 // s c a l e by s q r t ( nsamp ) per c e n t r a l l i m i t theorem combines // d i v i s i o n by nsamp to convert sums to means, and m u l t i p l i c a t i o n 121 // by s q r t ( nsamp ) s c a l e =1.0 f / s q r t ( ( f l o a t ) nsamp ) ; 123 f o r ( i t r i a l =0; i t r i a l <n t r i a l ; i t r i a l ++) mean [ i t r i a l ] = s c a l e ; 125 // bin means to compute histogram f o r ( i t r i a l =0; i t r i a l <n t r i a l ; i t r i a l ++) { 127 l b i n = 1.0 f ; f o r ( i b i n =0; i b i n <nbin ; i b i n++) { 129 i f ( ( l b i n <=mean [ i t r i a l ] ) && ( l b i n+dbin>mean [ i t r i a l ] ) ) h i s t [ i b i n ]+=1.0 f / ( ( f l o a t ) n t r i a l ) ; 131 l b i n+=dbin ; // output to t e r m i n a l f i r s t element o f each p a i r i s c e n t e r o f bin l b i n = 1.0 f +0.5 dbin ; 137 f o r ( i b i n =0; i b i n <nbin ; i b i n++) f p r i n t f ( fp, % e %10.2 e\n, l b i n+i b i n dbin, h i s t [ i b i n ] ) ; 139 // tack on two blank l i n e s f o r p l o t t i n g purposes f p r i n t f ( fp, \ n\n ) ; // c l e a n up 145 f r e e ( h i s t ) ; f r e e (mean ) ; f c l o s e ( fp ) ; r e t u r n 0 ; It also shows you how to put double-quotes in a formatted write statement The three standard files: The C i/o library defines three standard files, which are always open: stdin = keyboard input - can read from it, but not write to it ( r permission, in effect); stdout = terminal output - can write to it, but not read from it ( w ) - line buffered, that is, characters stored until a newline is encountered, then dumped to screen - you can lose output if for some reason the command does not complete (an error causes the program to abort, for example); stderr = unbuffered terminal output - every character goes straight through, useful for error messages So fprintf(stdout,...) is equivalent to printf(...), fscanf(stdin,...) to scanf(...). For redirection, (...) (file) captures stdout to the file, (...) & (file) captures stdout and stderr to the file. Since many apps (the gcc compiler, for example) write error messages to stderr, you should use the second form to capture output from them. 6
7 23.2 Long files: For files of length greater than the max int (approx. 4 GB for typical 4 byte ints), fseek and ftell are inadequate positioning tools. The 99 standard introduced the off t data type, which is identical to the largest integer supported by the compiler - for typical 64 bit machines, that s 8 byte long longs, adequate to represent any 64 bit address. The standard i/o library provides extensions fseeko and ftello, which work in exactly the same way as fseek and ftell except with off ts instead of ints. 24 Structures Arrays consist of some number of objects of identical type. The array data structure thus cannot accomodate an aggregation of objects of different types, which may be the natural way to express a data structure concept. For example, we have already remarked that arrays are unsatisfactory as data containers for vector data, as they do not know their own length : as a function argument, an array (however allocated) is merely a pointer to its first member. A more satisfactory data structure would combine a integer for length, and a pointer to a real type, for the array data with the presumption that the int is the length of the data array stored at the pointer (an interesting question: how would you enforce this relationship?). C provides a struct type to accommodate this type of data structure. Struct syntax takes this form: struct [structname] { [type1] [member1]; [type1] [member1]; [type1] [member1];... You access the members via the member access operator, denoted.. Thus for example in struct mystruct { char x; int y; float * z;... struct mystruct v; The members x, y, and z would be accessed as v.x; v.y; v.z;... 7
8 A full code example, that also uses the typedef command to define a variable type from a C struct: 2 #include <s t d i o. h> 4 typedef struct { 6 double x ; double y ; 8 10 point ; 12 main ( ) { 14 point p ; 16 p. x = 1. 2 ; p. y = 3. 2 ; p r i n t f ( p=(%f,% f )\ n, p. x, p. y ) ; The member access operator has high precedence - it s evaluated before anything else, so it s sometimes necessary to use parentheses to force the order of evaluation you want. K&R give a very good discussion of structures in Ch. 6 sections 1-4, and it is required reading for this week. I provide an example relevant to scientific programming, which will be discussed in class. 8
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 informationPROGRAMMAZIONE 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 informationCS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files
CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as
More informationCSci 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 informationLecture 8: Structs & File I/O
....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \
More informationUNIT 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 informationLecture 03 Bits, Bytes and Data Types
Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics
More information2009 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 informationInput / 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 informationGoals 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 informationContent. 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 informationI/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 informationI/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 informationSystems 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 informationCS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco
CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level
More informationENG120. 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 informationLecture 7: file I/O, more Unix
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 7: file
More informationQuick 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 informationDarshan 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 informationUNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.
UNIT-V Unit-5 File Streams Formatted I/O Preprocessor Directives Printf Scanf A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage
More informationCSC209H 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 informationProgramming 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 informationIntermediate 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 informationMode 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 informationUnit 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 informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationLecture 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.
Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special
More informationCS240: 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 informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Winter 2009 Lecture 7 Introduction to C: The C-Level of Abstraction CSE 303 Winter 2009, Lecture 7 1 Welcome to C Compared to Java, in rough
More informationStandard 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 information211: 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 informationIntroduction to file management
1 Introduction to file management Some application require input to be taken from a file and output is required to be stored in a file. The C language provides the facility of file input-output operations.
More informationC Basics And Concepts Input And Output
C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus
More informationWhat Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System
What Is Operating System? Operating Systems, System Calls, and Buffered I/O emacs gcc Browser DVD Player Operating System CS 217 1 Abstraction of hardware Virtualization Protection and security 2 Academic
More informationCSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-43 Exam Review February, 01 Presented by the RIT Computer Science Community http://csc.cs.rit.edu C Preprocessor 1. Consider the following program: 1 # include 3 # ifdef WINDOWS 4 # include
More informationCSI 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 informationCS 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 informationTHE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming
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)
More informationProcess 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 informationUNIX input and output
UNIX input and output Disk files In UNIX a disk file is a finite sequence of bytes, usually stored on some nonvolatile medium. Disk files have names, which are called paths. We won t discuss file naming
More information8. Structures, File I/O, Recursion. 18 th October IIT Kanpur
8. Structures, File I/O, Recursion 18 th October IIT Kanpur C Course, Programming club, Fall 2008 1 Basic of Structures Definition: A collection of one or more different variables with the same handle
More informationLecture 9: File Processing. Quazi Rahman
60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,
More informationShould you know scanf and printf?
C-LANGUAGE INPUT & OUTPUT C-Language Output with printf Input with scanf and gets_s and Defensive Programming Copyright 2016 Dan McElroy Should you know scanf and printf? scanf is only useful in the C-language,
More informationCS246 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 informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #47 File Handling In this video, we will look at a few basic things about file handling in C. This is a vast
More informationComputer 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 informationInput/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 informationCSCI 4210 Operating Systems CSCI 6140 Computer Operating Systems Homework 3 (document version 1.2) Multi-threading in C using Pthreads
CSCI 4210 Operating Systems CSCI 6140 Computer Operating Systems Homework 3 (document version 1.2) Multi-threading in C using Pthreads Overview This homework is due by 11:59:59 PM on Tuesday, April 10,
More informationCSE 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 informationC Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review
CS 2060 Variables Variables are statically typed. Variables must be defined before they are used. You only specify the type name when you define the variable. int a, b, c; float d, e, f; char letter; //
More information25.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 informationCopyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented
More informationComputational Methods of Scientific Programming Fall 2007
MIT OpenCourseWare http://ocw.mit.edu 12.010 Computational Methods of Scientific Programming Fall 2007 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
More informationCMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program
CMPT 102 Introduction to Scientific Computer Programming Input and Output Janice Regan, CMPT 102, Sept. 2006 0 Your first program /* My first C program */ /* make the computer print the string Hello world
More informationCS 220: Introduction to Parallel Computing. Input/Output II. Lecture 8
CS 220: Introduction to Parallel Computing Input/Output II Lecture 8 Today s Agenda Debugging and I/O Buffering I/O Streams Writing files 2/7/18 CS 220: Parallel Computing 2 Today s Agenda Debugging and
More informationLecture 9: Potpourri: Call by reference vs call by value Enum / struct / union Advanced Unix
....... \ \ \ / / / / \ \ \ \ / \ / \ \ \ V /,----' / ^ \ \.--..--. / ^ \ `--- ----` / ^ \. ` > < / /_\ \. ` / /_\ \ / /_\ \ `--' \ /. \ `----. / \ \ '--' '--' / \ / \ \ / \ / / \ \ (_ ) \ (_ ) / / \ \
More informationLANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING
C: Part 6 LANGUAGE OF THE C In part 6 of Steve Goodwins C tutorial we continue our look at file handling and keyboard input File handling Most software will at some time need to read from (or perhaps write
More informationCSE 124 Discussion (10/3) C/C++ Basics
CSE 124 Discussion (10/3) C/C++ Basics Topics - main() function - Compiling with gcc/makefile - Primitives - Structs/Enums - Function calls/loops - C++ Classes/stdtl - Pointers/Arrays - Memory allocation/freeing
More informationEE458 - Embedded Systems Lecture 4 Embedded Devel.
EE458 - Embedded Lecture 4 Embedded Devel. Outline C File Streams References RTC: Chapter 2 File Streams man pages 1 Cross-platform Development Environment 2 Software available on the host system typically
More informationFile 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 informationC How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e Storage of data in variables and arrays is temporary such data is lost when a program terminates. Files are used for permanent retention of data. Computers store files on secondary
More informationFile 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 informationCSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce
Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who
More informationCSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files
CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files ... and systems programming C basic syntax functions arrays structs
More informationCSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.
CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files... and systems programming C basic syntax functions arrays structs
More informationChapter 12. Files (reference: Deitel s chap 11) chap8
Chapter 12 Files (reference: Deitel s chap 11) 20061025 chap8 Introduction of File Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data
More informationFile 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 informationCSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine
More informationSystem 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 informationSlide 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 informationPointers 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 informationStandard File Pointers
1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf
More informationMemory 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 informationECE264 Spring 2014 Exam 2, March 11, 2014
ECE264 Spring 2014 Exam 2, March 11, 2014 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.
More informationC 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 informationCSC209 Review. Yeah! We made it!
CSC209 Review Yeah! We made it! 1 CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files 2 ... and C programming... C basic syntax functions
More informationC programming basics T3-1 -
C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of
More informationComputer System and programming in C
File Handling in C What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact
More informationLecture 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 informationCh 11. C File Processing (review)
Ch 11 C File Processing (review) OBJECTIVES To create, read, write and update files. Sequential access file processing. Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits
More informationBasic and Practice in Programming Lab 10
Basic and Practice in Programming Lab 10 File (1/4) File management in C language FILE data type (strictly, data structure in C library) Three operational modes Read/Write/Append fopen A library function
More informationC Programming 1. File Access. Goutam Biswas. Lect 29
C Programming 1 File Access C Programming 2 Standard I/O So far all our I/O operations are read from the standard input (stdin - keyboard) and write to the standard output (stdout - VDU) devices. These
More informationComputer 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 informationHere's how you declare a function that returns a pointer to a character:
23 of 40 3/28/2013 10:35 PM Violets are blue Roses are red C has been around, But it is new to you! ANALYSIS: Lines 32 and 33 in main() prompt the user for the desired sort order. The value entered is
More informationComputer Programming: Skills & Concepts (CP) Files in C
CP 20 slide 1 Tuesday 21 November 2017 Computer Programming: Skills & Concepts (CP) Files in C Julian Bradfield Tuesday 21 November 2017 Today s lecture Character oriented I/O (revision) Files and streams
More informationFile I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C
File I/O, Project 1: List ADT Bryce Boe 2013/07/02 CS24, Summer 2013 C Outline Memory Layout Review Pointers and Arrays Example File I/O Project 1 List ADT MEMORY LAYOUT REVIEW Simplified process s address
More informationC File Processing: One-Page Summary
Chapter 11 C File Processing C File Processing: One-Page Summary #include int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be
More informationCMPE-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 informationOrganization of a file
File Handling 1 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example: Consider keeping students records 100 students
More informationPlay with FILE Structure Yet Another Binary Exploitation Technique. Abstract
Play with FILE Structure Yet Another Binary Exploitation Technique An-Jie Yang (Angelboy) angelboy@chroot.org Abstract To fight against prevalent cyber threat, more mechanisms to protect operating systems
More informationFiles 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 informationDS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29
DS: CS 11002 Computer Sc & Engg: IIT Kharagpur 1 File Access DS: CS 11002 Computer Sc & Engg: IIT Kharagpur 2 Standard I/O So far all our I/O operations are read from the standard input (stdin - keyboard)
More informationDATA STRUCTURES USING C
DATA STRUCTURES USING C File Handling in C Goals By the end of this unit you should understand how to open a file to write to it. how to open a file to read from it. how to open a file to append data to
More informationC-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 informationCSE 12 Spring 2016 Week One, Lecture Two
CSE 12 Spring 2016 Week One, Lecture Two Homework One and Two: hw2: Discuss in section today - Introduction to C - Review of basic programming principles - Building from fgetc and fputc - Input and output
More informationLecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 8 Data Files Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To be able to create, read, write and update
More informationHeap 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 informationProcedures, Parameters, Values and Variables. Steven R. Bagley
Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.
More informationFile I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
File I/O Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Unix Files A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices
More informationOutline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging
Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture
More information