Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab www.ai2lab.org Short Course on Programming in C/C++

Slides:



Advertisements
Similar presentations
C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Advertisements

C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
C Language.
Files in C Rohit Khokher.
Structures in C.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Kernighan/Ritchie: Kelley/Pohl:
Memory and Files Dr. Andrew Wallace PhD BEng(hons) EurIng
Winter2015 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University C: Advanced Topics.
Text File Input and Output. Overview Text File Buffered I/O Functions fopen Function Demo of File Write and Read.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Structs. Structures We already know that arrays are many variables of the same type grouped together under the same name. Structures are like arrays except.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
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.
Programming Practice Introduction Tree Operations. Binary Search Tree. File Processing Create, read, write and update files. Sequential.
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.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
C Programming Lecture 12 : File Processing
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 11 : September 18.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Adv. UNIX:fp/101 Advanced UNIX v Objectives of these slides: –a more detailed look at file processing in C Special Topics in Comp. Eng.
Files A collection of related data treated as a unit. Two types Text
CS 241 Section Week #5 9/22/11. 2 Topics This Section File I/O Advanced C.
STRUCTURES. INTRODUCTION A structure is same as that of records. It stores related information about an entity. Structure is basically a user defined.
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
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.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
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.
Advanced Programming in the UNIX Environment Hop Lee.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
Lecture 12 CIS 208 Friday, March 3rd , 2005.
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
TMF1414 Introduction to Programming
Introduction to Computer Programming Lecture 18 Binary Files
CGS 3460, Lecture 41 Apr 21, 2006 Hen-I Yang
CSC215 Lecture Input and Output.
CS111 Computer Programming
File Input/Output.
DATA HANDLING.
Lecture 9 Structure 1. Concepts of structure Pointers of structures
Chapter 11 – File Processing
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
C Programming Lecture-15 File I/O
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
Text and Binary File Processing
File Input and Output.
Henning Schulzrinne Columbia University
I/O CS580U - Fall 2018.
Presentation transcript:

Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++ Organized by Onur Pekcan Contributor Selim Temizer Instructor Hasan Yılmaz

Week 2 – Lecture1 Today We will cover; Structures and Unions  Basic of Structures  Structures and Functions  Structures and Arays  Self-Referential Structures(Structures Containing Pointers)  Unions & Enumerations File Processing with C  Reading from & Writing to Files 2

Basics of Structures struct person{ int age; char gender; char * name; }; struct person ali = {10, ‘m’, “Ali Veli”}; Why do we need them? 1.Grouping 2.Modularity 3.Flexibility 4.… printf("%d %c %s\n", ali.age, ali.gender, ali.name); Structures and why we need them 3

Basics of Structures Syntax of Structures  Definition struct { ; …. ; }; Usage  struct new_str,, …;  Intialization:  struct new_str = {value1, value2, …, valueN};  Individual Elements:  new_str. =  Basically, you can use members of a struct like a variable. 4

Basics of Structures Initialization of Structures struct student { int age; char gender; char * name; int grades[3]; }; struct student ali = {21, ‘m’, “Ali Veli”, {60, 70, 80}}; struct student veli = {21};  initializes the rest of the members to zero. 5

Basics of Structures Typing and Assignment of structs The following are two different data types for C: struct {char a; int b;} var1; struct {char a; int b;} var2; struct str1 { char a; int b; } var3; struct str2 { char a; int b; } var4; For the first and the second cases, since no explicit name was given to the structure, we can’t declare a new variable that has the same type as var1 and var2. 6

Basics of Structures Typing and Assignment of structs You can assign structs of the same type to each other. E.g.: struct str_type {char a; int b;}; struct str_type a = {‘m’, 10}; struct str_type b = a; 7

Basics of Structures The “.” (dot) operator For accessing the members of a structure, we use the dot operator: struct str_type {char a; int b;} var1; var1.a = ‘m’; The dot operator has the same precedence with [], & and -> These operators are left-to-right associative. 8

Basics of Structures Size of a struct You can use the sizeof operator on structures. The size of a struct may be more than the sum of the sizes of its members. For example: struct str_type {char a; int b;} var1;  The size of var1 is probably more than 5 (due to data alignment with memory words) However, the following is probably 2 times the size of an int: struct str_type2 {int a; int b;} var2; 9

Basics of Structures Nested structures You can use one struct within another one: struct name_str { char * first_name; char * last_name; }; struct person { struct name_str name; int age; char gender; } struct person ali = {{“ali”, “veli”}, 10, ‘m’}; struct name_str name = {“veli”, “deli”}; ali.name = name; ali.name.first_name = “Deli” 10

Basics of Structures Structure Pointers struct person ali = {{“ali”, “veli”}, 10, ‘m’}; struct person * person_ptr; person_ptr = &ali; (*person_ptr).age = 20;  person_ptr->age = 20; Using pointers to structures is better/faster than using structures directly especially in the case of function calls. 11

Basics of Structures typedef typedef struct struct_name { /* variables */ } struct_name_t; struct_name_t struct_name_t_instance; 12

Example #include struct database { int id_number; int age; float salary; }; int main() { struct database employee; /*There is now an employee variable that has modifiable*/ // variables inside it. employee.age = 22; employee.id_number = 1; employee.salary = ; } #include struct database { int id_number; int age; float salary; }; int main() { struct database *employee; /*There is now an employee variable that points a structure*/ // variables inside where it points. employee->age = 22; employee->id_number = 1; employee->salary = ; } 13

Example #include struct student { int id; char *name; float percentage; } student1, student2, student3; int main() { struct student st; student1.id=1; student2.name = "Angelina"; student3.percentage = 90.5; printf(" Id is: %d \n", student1.id); printf(" Name is: %s \n", student2.name); printf(" Percentage is: %f \n", student3.percentage); return 0; } Output: Id is: 1 Name is: Angelina Percentage is:

Structures & Functions You can define a new structure within a function. In that case, the definition of that structure is accessible only within that function. You can pass structures as parameters to a function. A function can return a structure as its value. Since call-by-value means copying the members of structures, pointers are preferred as function parameters for structures. 15

Structures & Functions What is wrong with the following? struct str {int a; char b;}; struct str * f() { struct str a; return &a; } Correct way: struct str {int a; char b;}; struct str * f() { struct str * a = (struct str *) malloc( sizeof(struct str) ); return a; } 16

Structures and Arrays Arrays of structures struct student { int age; char * name; int grades[3]; }; struct student shortc_students[20]; struct student students[2] = { {10, “Ali”, {10, 20, 30}, {20, “Veli”, {20, 30, 40}} } 17

Self Referential Structures Structures Containing Pointers Members of a structure can be pointers, as we have seen before: struct student { int age; char * name; int * grades; }; A structure can include a pointer to itself: struct student { int age; char * name; struct student * friends; int num_of_friends; }; 18

Family Tree Example with Structures  Each person has: – a name, age, social security number. – a father and a mother. – siblings – friends – daughters and sons  Given such a family tree, you can implement functions to find:  the grandparents of a given person,  the cousins of a given person,  the grandsons of a person,  etc. 19

Structures & Pointers: Trees 20

Structures & Pointers: Trees Traversal of a tree Pre-order traversal: – A C M N X O In-order traversal: – C N M A X O Post-order traversal: – N M C O X A 21

Structures & Pointers: Trees 22

Structures & Pointers: Linked Lists 23

Structures & Pointers: Doubly Linked Lists 24

Application of Linked Lists: Queues 25

Problem 1 Write a C program to store the information of 30 students(name, roll number and marks) using structures. Then, display the information of students 26

Problem 2 Write a C program to add two distances entered by user in feet-inch system. To perform this program, create a structure containing elements feet and inch. [Note: 12 inch = 1feet] 27

Unions Allows different types of data to share the same memory location! Variables c, I, d and cp share the same memory location The size of data is the biggest of the following: o sizeof(c) o sizeof(i) o sizeof(d) o sizeof(cp) 28

Unions 29

Enumerations 30

Enumerations They are essentially integers. The members get values starting from 0. Values can be assigned to the members as follows: 31

struct vs union vs enum What is the difference between them? Why do we have them? 32

Example Assume that you are given random set of characters of three types arbitrarily: – white space – alphabet letters – numbers – others Orn: The problem is to partition these different types of data into homogeneous parts & print the partitions when requested. 33

File Processing with C Files Files are just collections of bytes – One dimensional data from bytes When we work with files, they are processed byte by byte … 34

Files & Streams File: a stream of bytes – Text stream – Binary stream Types of I/O: – Unbuffered – Fully buffered – Line buffered 35

Buffers & Buffering Why do we have buffers? – Synchronization between processes or hardware components. Ex: I/O, telecommunication networks. – Pooling for collecting data before processing: Ex: printing, online video streaming. –…–… 36

FILE structure When a file is opened, a FILE structure (called file pointer) is associated. FILE holds the following which are necessary for controlling a stream: – the current position in the file – error indicator – end-of-file indicator – pointer to the associated buffer After the processing is finished, FILE should be closed. 37

Standard Streams in C When a program starts, it is given three streams: – stdin: terminal keyboard or an input file – stdout: screen or any re-directed file – stderr: screen or any re-directed file Ex: –./my_prog out.txt 2> err.txt Why do we have stderr? 38

Types of File Processing Sequential – Read the bytes in sequence Random Access – Read the bytes at a given position in the file 39

Opening and Closing Files in C FILE* fopen( const char *filename, const char * filemode ) int fclose(FILE *filepointer) int fflush(FILE *filepointer) filemode can be: – “r”  Open file for reading. – “w”  Open file for writing. Delete old contents if it exists already. – “a”  Create a new file or append to the existing one. – “r+”, “w+”, “a+”  input & output – An additional “b” can be appended to the file mode for binary I/O. 40

Operations on Files int remove(const char *filename) int rename( const char *oldname, const char *newname) 41

Sequential File I/O in C int fscanf(FILE *fp, const char * format, …) int fprintf(FILE *fp, const char * format, …) int fgetc(FILE *fp) int fputc(int c, FILE *fp) char *fgets(char *s, int n, FILE *fp) char *fputs(const char *s, FILE *fp) 42

Random Access in C int fseek(FILE *fp, long offset, int whence) long ftell(FILE *fp) void rewind(FILE *fp) whence: – SEEK_SET, SEEK_END, SEEK_CUR size_t fread(void *s, size_t sz, size_t n, FILE *fp) size_t fwrite(const void *s, size_t sz, size_t n, FILE *fp) 43

Error Handling in File I/O int feof(FILE *fp) int ferror(FILE *fp) void clearerr(FILE *fp) 44

More on Preprocessing #ifdef #endif 45

Example Write a program that does simple encryption on a text file. 46