010.133 Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Kernighan/Ritchie: Kelley/Pohl:
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 8 - Characters and Strings Outline 8.1Introduction.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
A First Book of ANSI C Fourth Edition Chapter 10 Data Files.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
File Handling Spring 2013Programming and Data Structure1.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
File Handling In C By - AJAY SHARMA. We will learn about- FFile/Stream TText vs Binary Files FFILE Structure DDisk I/O function OOperations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Characters and Strings File Processing Exercise C Programming:Part 3.
File IO and command line input CSE 2451 Rong Shi.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Lecture 8a: File I/O BJ Furman 21MAR2011. Learning Objectives Explain what is meant by a data stream Explain the concept of a ‘file’ Open and close files.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Pointers *, &, array similarities, functions, sizeof.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
C Programming Lecture 12 : File Processing
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
CS 1704 Introduction to Data Structures and Software Engineering.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Files A collection of related data treated as a unit. Two types Text
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
C is a high level language (HLL)
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
Gator Engineering Google Code Jam 2015 Copyright © 2008 W. W. Norton & Company. All rights reserved. 1.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
CSE 220 – C Programming Pointers.
Chapter 4 File Processing
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Lecture 11 File input/output
Introduction to C CSE 2031 Fall /3/ :33 AM.
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
Computer Science 210 Computer Organization
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
CSE1320 Files in C Dr. Sajib Datta
Lecture 15 Files.
CSC215 Lecture Input and Output.
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
Text and Binary File Processing
File Input and Output.
Module 12 Input and Output
Introduction to C CSE 2031 Fall /15/2019 8:26 AM.
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
Presentation transcript:

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Pointers (revisited) int i = 4, j = 6, *p = &i, *q = &j, *r; if (p == &i)...; if (p == (& i))...;... = **&p;... = *(*(& p));... = 9 * *p / *q + 8;... = (((9*(*p)))/(*q)) + 8; *(r = &i) *= *p; (* (r = (& j))) *= (* p);

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Pointers (contd.) int *p; float *q; void *v; /* void*: generic pointer type */ p = 0; p = v = q; p = (int *) 3; p = (int *) q;

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Pointers as Function Arguments Suppose we want to make a function that returns the maximum and the minimum of three integers a, b, and c We cannot pass the results with the return mechanism of the function because we need to return two values Use pointers The code in the next slide shows such a function We can call it by maxmin(a, b, c, &max, &min);

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Pointers as Function Arguments (contd.) void maxmin(int a, int b, int c, int *pmax, int *pmin) { if (a >= b) { if (a >= c) { /* a is maximum */ *pmax = a; if (b >= c) *pmin = c; else *pmin = b; } else { /* c > a >= b */ *pmax = c; *pmin = b; } } else { if (b >= c) { /* b is maximum */ *pmax = b; if (a >= c) *pmin = c; else *pmin = a; } else { /* c > b > a */ *pmax = c; *pmin = a; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Swap Function #include void swap(int*, int*); int main(void) { int x = 4, y = 5; swap( &x, &y ); printf(“%d %d\n”, x, y); return 0; } void swap( int *p, int *q ) { int tmp; tmp = *p; *p = *q; *q = tmp; } #include void swap(int, int); int main(void) { int x = 4, y = 5; swap( x, y ); printf(“%d %d\n”, x, y); return 0; } void swap( int p, int q ) { int tmp; tmp = p; p = q; q = tmp; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Pointers and Arrays An array name is actually a constant pointer Its value cannot be changed When x is an array, x[i] is the same as *(x + i) When p is a pointer, *(p + i) is the same as p[i] #define N 100 int a[N], i, *p, sum = 0; for(p = a; p < &a[N]; p++) sum += *p; for(i = 0; i < N; i++) sum += *(a + i); for(p = a, i = 0; i < N; i++) sum += p[i];

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Pointer Arithmetic If p is a pointer to a particular type, the expression p + 1 gives the address for the storage of the next variable of that type double a[10], *p, *q; p = a; /* p points to the first element of a */ q = p + 2; /* q points to the third element of a */ printf(“%d\n”, q – p) /* q - p is 2 */ printf(“%d\n”, (int) q – (int) p) /* 16 */

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Arrays as Function Arguments The base address of the array is passed to the function double sum(double x[], int n) /* ≡ double sum(double *x, int n) */ { int i; double sum = 0.0; for (i = 0; i < n; i++) sum += x[i]; return sum; } double y[ 100 ]; … sum(y, 100); sum(y, 20); sum(&y[10], 20); sum(y + 10, 20);

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Arrays and Strings A character array can be initialized with a string constant when it is declared char str[12] = “programming”; The length of str should be the number of characters in the string constant plus 1 The last byte contains the null character The length of the array in the example above may be omitted char str[] = “programming”; 12 bytes are assigned to str by the compiler

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Arrays and Strings (contd.) If there is no room for the null character as in the example below, carr cannot have a terminating null character and it is not a string char carr[11] = “programming”; It is an array of characters The conversion specification for a string in both printf and scanf is %s

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee String Constants String constants are written between double quotes Treated as a pointer The value is the base address of the string char *p = “abc”; printf(“%s %s\n”, p, p+1); “abc”[2] *(“abc” + 2) char s[] = “abc”; char s[] = { ‘a’, ‘b’, ‘c’, ‘\0’ };

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee String Pointers Consider the following declarations: char str[] = “programming”; char *pstr = “programming”; The first one declares a string variable str, i.e., an array of characters We can modify the characters in str str[3] = ‘t’; The second one declares a pointer variable pstr, which points to a string constant We may modify the pointer itself, but may not modify characters in the string constant

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Pointer Arrays Suppose we want to store an array of strings such as country names The best way is to use an array of pointers char *pcountry[] = {“Korea”, “China”, “Japan”, “U.S.A.”, “Russia”}; Then pcountry[0] is a pointer that points to “Korea”, pcountry[1] is a pointer to “China”, etc.

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Simple Cryptosystem A cryptosystem consists of an encryption function and a decryption function The encryption function gets a plaintext and a key, and produces a ciphertext The decryption function gets a ciphertext and a key, and produces a plaintext If the decryption key is the same as the encryption key, the decryption function should produce the original plaintext

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Simple Cryptosystem (contd.) The Shift Cipher is one of the simple cryptosystems In fact, it is too simple to be secure, but it was actually used in history Assume that plaintexts and ciphertexts are strings of lowercase alphabet letters The key is an integer k between 0 and 25

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Simple Cryptosystem (contd.) The encryption function shifts each letter of the plaintext to the right by k positions (modulo 26) For example, if the key is 3, each letter of the plaintext is changed to a ciphertext letter as shown in the table below plaintextabcdefghijklmnopqrstuvwxyz ciphertextdefghijklmnopqrstuvwxyzabc

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Simple Cryptosystem (contd.) If the plaintext is “hello” and the key is 3, the ciphertext becomes “khoor” The decryption function shifts each letter of the ciphertext to the left by k positions (modulo 26)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee Encryption Function #include #define SMAX 100 #define KMOD 26 void EncShift(char ptext[], char ctext[], int key) { int i=0; while (ptext[i] != '\0') { ctext[i] = (ptext[i]-'a'+key) % KMOD + 'a'; i++; } ctext[i] = '\0'; } int main(void) { char ptext[SMAX], char ctext[SMAX]; int key; printf("Enter plaintext: "); scanf("%s", ptext); printf("Enter key: "); scanf("%d", &key); EncShift(ptext, ctext, key); printf("Ciphertext: %s\n", ctext); return 0; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O In C, a stream is a source of input or a destination of output A text stream is a sequence of lines and each line has zero or more characters and is terminated by ‘\n’

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O (contd.) provides three standard streams stdin (standard input): keyboard stdout (standard output): screen stderr (standard error): screen Printf gets input from stdin, and scanf sends output to stdout C also provides two simple I/O functions: int getchar(void) Reads the next character from stdin and returns it int putchar(int c) Prints character c into stdout

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O (contd.) Instead of standard input and output, a program can access a file for its input and output A file pointer (stream) that points to a file (whose type is FILE) FILE *fp;

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O Operations FILE *fopen(const char *filename, const char *mode) Opens the filename file and returns a file pointer, or it returns NULL if the filename file does not exist The modes for text files are, “r” open for reading (the file must exist) “w”open for writing (discard previous contents if any) “a”open for appending (the file is created if it does not exist) “r+”open for reading and writing (the file must exist) “w+”open for reading and writing (discard previous contents if any) “a+”open for reading and appending (the file is created if it does not exist)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O Operations (contd.) int fclose(FILE *stream) Closes stream int fgetc(FILE *stream) Returns the next character of stream, or EOF if end of file or error occurs int fputc(int c, FILE *stream) Writes character c on stream char *fgets(char *s, int n, FILE *stream) Reads at most the next n-1 characters into array s, stops if a newline is encountered (the newline is included in s) Returns s, or NULL if end of file or error occurs

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O operations (contd.) int fputs(const char *s, FILE *stream) Writes string s (which need not to contain a newline) on stream long ftell(FILE *stream) Returns the current file position of stream Data type long means a long integer int fseek(FILE *stream, long offset, int origin) Sets the file position for stream A subsequent read or write will access data at the new position. origin may be SEEK_SET (beginning), SEEK_CUR (current position), or SEEK_END (end of file) For a text stream, offset must be zero, or a value returned by ftell in which case origin must be SEEK_SET (fseek moves the position to the beginning or end of a text stream, or to a place that was visited previously)

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O Example Copies the contents of input.txt to output.txt EOF is an integer constant defined in and it indicates ‘end of file’

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O Example (contd.) #include int main(void) { FILE *fp1, *fp2; int c; fp1 = fopen("input.txt", "r"); fp2 = fopen("output.txt", "w"); while ((c = fgetc(fp1)) != EOF) fputc(c, fp2); fclose(fp1); fclose(fp2); return 0; }

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O Example (contd.) Writes two strings into test.txt, sets the file position to the beginning, and reads the first line It will print “alphabet” when test.txt contains the following two lines: alphabet abcdefghijklmnopqrstuvwxyz

Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee File I/O Example (contd.) #include int main(void) { FILE *fp; char *pstr = "abcdefghijklmnopqrstuvwxyz"; char buf[30]; fp = fopen("test.txt", "w+"); if(fp == NULL) { printf("file open error\n"); return -1; } fputs("alphabet\n", fp); fputs(pstr, fp); fseek(fp, 0, SEEK_SET); fgets(buf, 30, fp); printf("%s", buf); fclose(fp); return 0; }