+ All Categories
Home > Documents > C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics...

C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics...

Date post: 21-May-2020
Category:
Upload: others
View: 8 times
Download: 0 times
Share this document with a friend
84
Copyright 2000-2019 Networking Laboratory C/C++ programming overview Sungkyunkwan University Hyunseung Choo [email protected]
Transcript
Page 1: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Copyright 2000-2019 Networking Laboratory

C/C++ programming overview

Sungkyunkwan University

Hyunseung Choo

[email protected]

Page 2: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Contents Functions

Invocations Function

Function Definitions Return

statements

Function Prototypes

Call by value and call by

reference

Networking Laboratory 2/84

C basics

“Hello World" Program

Data Types & Variables

printf()

Arithmetic & Logical Operations

Conditionals

Loops

Arrays & Strings

Pointer and Array

Programming Tips

File I/O in C++

General File I/O Steps

C++ streams

File I/O Example

More Input/Output File-

Related Functions

Page 3: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Hello World Program

The source code

#include <stdio.h>

int main()

{

printf("Hello World\n");

return(0);

}

Page 4: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Hello World Program

How to compile?

$ gcc hello.c –o hello

gcc compiling command

hello.c source file

hello compiler-generated executable file

Note: the default output filename is “a.out”

Page 5: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

How to execute?

./hello

“./ ” indicates the following file “hello” resides under the

current directory.

Hello World Program

Page 6: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Name Description Size* Range*

char Character or small

integer

1 byte signed: -128 to 127

unsigned: 0 to 255

short int

(short)

Short integer 2 bytes signed: -32768 to 32767

unsigned: 0 to 65535

int Integer 2 or

4 bytes

signed: -32768 to 32767

unsigned: 0 to 65535 Or

signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295

long int

(long)

Long integer 4 bytes signed: -2147483648 to 2147483647

unsigned: 0 to 4294967295

float Floating point number 4 bytes 3.4e +/- 38 (7 digits)

double Double precision

floating point number

8 bytes 1.7e +/- 308 (15 digits)

Data types

Page 7: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

int length = 100;

char num = ‘9’; //The actual value is 57

float deposit = 240.5;

unsigned short ID = 0x5544;

Try the following statements, and see what happens:

unsigned char value = -1;

printf(“The value is %d \n”, value);

unsigned char value = 300;

printf(“The value is %d \n”, value);

Variable Declaration

Page 8: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Result

Definition Memory layout Display comment

unsigned char

value = -1

11111111 255

unsigned char

value = 300

00101100 44 overflow

Page 9: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Local variable

Local variables are declared within the body of a function, and can

only be used within that function.

Static variable

Another class of local variable is the static type. It is specified by

the keyword static in the variable declaration.

The most striking difference from a non-static local variable is, a

static variable is not destroyed on exit from the function.

Global variable

A global variable declaration looks normal, but is located outside

any of the program's functions. So it is accessible to all functions.

Variable types

Page 10: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

int global = 10; //global variable

int func (int x)

{

static int stat_var; //static local variable

int temp; //(normal) local variable

int name[50]; //(normal) local variable

……

}

An example

Page 11: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Variable Definition vs Declaration

Definition Tell the compiler about the variable: its type and

name, as well as allocated a memory cell for the

variable

Declaration Describe information “about” the variable,

doesn’t allocate memory cell for the variable

DEFINITION = DECLARATION + SPACE RESERVATION

struct _tagExample { int a; int b; }; struct _tagExample example;

Declaration Definition

Page 12: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

printf() function

The printf() function can be instructed to print integers, floats and string properly.

The general syntax is

printf( “format”, variables);

An exampleint stud_id = 5200;

char * name = “Choo”;

printf(“%s ‘s ID is %d \n”, name, stud_id);

Page 13: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Format Identifiers

%d decimal integers

%x hex integer

%c character

%f float and double number

%s string

%p pointer

How to specify display space for a variable?

printf(“The student id is %5d \n”, stud_id);

The value of stud_id will occupy 5 characters space in

the print-out.

printf() function

Page 14: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Why “\n”

It introduces a new line on the output screen.

\a alert (bell) character \\ backslash

\b backspace \? question mark

\f formfeed \’ single quote

\n newline \” double quote

\r carriage return \000 octal number

\t horizontal tab \xhh hexadecimal number

\v vertical tab

printf() function

Page 15: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Arithmetic Operations

Page 16: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Arithmetic Assignment Operators

Page 17: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Increment and Decrement Operators

awkward easy easiest

x = x+1; x += 1 x++

x = x-1; x -= 1 x--

Page 18: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Example

Arithmetic operatorsint i = 10;

int j = 15;

int add = i + j; //25

int diff = j – i; //5

int product = i * j; // 150

int quotient = j / i; // 1

int residual = j % i; // 5

i++; //Increase by 1

i--; //Decrease by 1

Page 19: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

int i = 10;

int j = 15;

float k = 15.0;

j / i = ?

j % i = ?

k / i = ?

k % i = ?

Example

Page 20: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

The Answer

j / i = 1;

j % i = 5;

k / i = 1.5;

k % i It is illegal.

Note: For %, the operands can only be integers.

Example

Page 21: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Logical Operations

What is “true” and “false” in C

In C, there is no specific data type to represent “true” and “false”. C uses

value “0” to represent “false”, and uses non-zero value to stand for “true”.

Logical Operators

A && B => A and B

A || B => A or B

A == B => Is A equal to B?

A != B => Is A not equal to B?

Page 22: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

A > B => Is A greater than B?

A >= B => Is A greater than or equal to B?

A < B => Is A less than B?

A <= B => Is A less than or equal to B?

Don’t be confused

&& and || have different meanings from & and |.

& and | are bitwise operators.

Logical Operations

Page 23: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Short circuiting

Short circuiting means that we don't evaluate the second

part of an AND or OR unless we really need to.

Some practices

Please compute the value of the following logical

expressions?

Page 24: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

int i = 10; int j = 15; int k = 15; int m = 0;

if( i < j && j < k) =>

if( i != j || k < j) =>

if( j<= k || i > k) =>

if( j == k && m) =>

if(i) =>

if(m || j && i ) =>

Example

Page 25: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

int i = 10; int j = 15; int k = 15; int m = 0;

if( i < j && j < k) => false

if( i != j || k < j) => true

if( j<= k || i > k) => true

if( j == k && m) => false

if(i) => true

if(m || j && i ) => true

Did you get the correct answers?

Example

Page 26: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Conditionals

if statement

Three basic formats,

if (expression){

statement …

}

if (expression) {

statement …

}else{

statement …

}

Page 27: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

if (expression) {

statement…

} else if (expression) {

statement…

} else{

statement…

}

Conditionals

Page 28: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

if(score >= 90){

a_cnt ++;

}else if(score >= 80){

b_cnt++;

}else if(score >= 70){

c_cnt++;

}else if (score>= 60){

d_cnt++

}else{

f_cnt++

}

Example

Page 29: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

switch (expression)

{

case item1:

statement;

break;

case item2:

statement;

break;

default:

statement;

break;

}

The switch statement

Page 30: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Loops

for statement

for (expression1; expression2; expression3){

statement…

}

expression1 initializes;

expression2 is the terminate test;

expression3 is the modifier;

Page 31: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

int x;

for (x=0; x<3; x++)

{

printf("x=%d\n",x);

}

First time: x = 0;

Second time: x = 1;

Third time: x = 2;

Fourth time: x = 3; (don’t execute the body)

Example

Page 32: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

while (expression) {

statement …

}

while loop exits only when the expression is false.

An example

int x = 3;

while (x>0) {

printf("x=%d n",x);

x--;

}

The while statement

Page 33: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

for <==> while

for (expression1; expression

2; expression3){

statement…

}

expression1;

while (expression2)

{

statement…;

expression3;

}

equals

Page 34: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Arrays & Strings

Arrays

int ids[50];

char name[100];

int table_of_num[30][40];

Accessing an array

ids[0] = 40;

i = ids[1] + j;

table_of_num[3][4] = 100;

Note: In C Array subscripts start at 0 and end one less than the array size. [0 .. n-1]

Page 35: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Strings are defined as arrays of characters.

The only difference from a character array is, a symbol

“\0” is used to indicate the end of a string.

For example, suppose we have a character array, char

name[8], and we store into it a string “Choo”.

Note: the length of this string 4, but it occupies 5 bytes.

C h o o \0

Strings

Page 36: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Functions

Networking Laboratory 36/78

Page 37: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Invocations Function (1/3)

Function

A C program consists of one or more functions

Every c-program must contain one main() Function

In the case of repeated codes, define the function and call the

function whenever necessary to improve the simplicity

Function types:

Library functions : System Predefined-Functions

User-defined functions : Functions created by Programmers

Function Invocation

Function call: used in the form Function_name().

Function end: the control point go back to the place where the function

was called

Networking Laboratory 37/78

Page 38: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Invocations Function (2/3)

Networking Laboratory 38/78

Page 39: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Invocations Function (3/3)

Networking Laboratory 39/78

Page 40: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Function Definitions (1/2)

Before the function is called, the function must be defined

in the following format.

Networking Laboratory 40/78

Page 41: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Function Definitions (2/2)

Parameter Type List

Specify the order and data types corresponding to the arguments

passed when calling the function.

Specify the data types and the order in which the arguments are

passed in the function call.

Can be used as identifiers in the function body

Return type

Type of return statement must be matched with return type of the function

Default type : integer type

void type : void if there is no return value

Networking Laboratory 41/78

Page 42: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

The Return Value

Networking Laboratory 42/78

Page 43: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Function Prototypes (1/2)

Function is defined before the main function

선언형식

return-type function_name (parameter type list);

Networking Laboratory 43/78

Page 44: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Function Prototypes (2/2)

If the type of the passing parameter does not match the

type of the defined argument, it is converted to the type

specified in the function prototype.

Networking Laboratory 44/78

Page 45: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Function Definition Order

A general sequence of programs written in one file

1. #include, #define statements

2. Enumeration types and typedef

3. struct definition

4. Function Prototypes

5. main() Function

6 Function Definitions

Networking Laboratory 45/78

Page 46: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Developing Large Program (2/2)

Networking Laboratory 46/78

Page 47: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Call by Value and Call by Reference

Call-by-Value

When Function Invocation occurs, a memory area is newly created

for the parameter to receive the value of the argument, and the

value of the argument is copied to the new memory area.

Even if you use Function Invocation parameter as an identifier and

change its value in the content of the function, the actual argument

value is not changed by using another memory area

Call-by-Reference

When Function Invocation occurs, it passes the address of the

argument.

The actual argument value is changed when the value is changed

in the function

Networking Laboratory 47/78

Page 48: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Example of Call by Value

Networking Laboratory 48/78

Page 49: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Example of Call by Reference

Networking Laboratory 49/78

Page 50: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Pointers and Arrays

Networking Laboratory 50/78

Page 51: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Pointers and Arrays

Pointers and arrays are very closely linked in C.

Array elements arranged in consecutive memory locations

Accessing array elements using pointers

int ids[50];

int * p = &ids[0];

p[i] <=> ids[i]

Pointers and Strings

A string can be represented by a char * pointer.

Pointers and Arrays

Page 52: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Char name[50];

name[0] = ‘C’;

name[1] = ‘h’;

name[2] = ‘o’;

name[3] = ‘o’;

name[4] = ‘\0’;

char * p = &name[0];

printf(“The name is %s \n”, p);

Note: The p represents the string “Choo”, but not the array

name[50].

Pointers and Arrays

Page 53: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Command-Line Argument

In C you can pass arguments to main() function.

main() prototype

int main(int argc, char * argv[]);

argc indicates the number of arguments

argv is an array of input string pointers.

How to pass your own arguments?

./hello 10

Page 54: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

What value is argc and argv?

Let’s add two printf statement to get the value of argc and argv.

#include <stdio.h>

int main(int argc, char * argv[]);)

{

int i=0;

printf("Hello World\n");

printf(“The argc is %d \n”, argc);

for(i=0; i < argc; i++){

printf(“The %dth element in argv is %s\n”, i, argv[i]);

}

return(0);

}

Command-Line Argument

Page 55: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

The output

The argc is 2

The 0th element in argv is ./hello

The 1th element in argv is 10

The trick is the system always passes the name of the executable file as

the first argument to the main() function.

How to use your argument?

Be careful. Your arguments to main() are always in string format.

Taking the above program for example, the argv[1] is string “10”, not a

number. You must convert it into a number before you can use it.

Command-Line Argument

Page 56: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Data Structure

A data structure is a collection of one or more variables, possibly of different

types.

An example of student record

struct stud_record{

char name[50];

int id;

int age;

int major;

……

};

Page 57: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

A data structure is also a data type

struct stud_record my_record;

struct stud_record * pointer;

pointer = & my_record;

Accessing a field inside a data structure

my_record.id = 10; “.”

or

pointer->id = 10; “->”

Data Structure

Page 58: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

File I/O in C++

Networking Laboratory 58/78

Page 59: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Using Input/Output Files

A computer file

is stored on a secondary storage device (e.g., disk);

is permanent;

can be used to ◼ provide input data to a program ◼ or receive output data from a program◼ or both;

should reside in Project directory for easy access;

must be opened before it is used.

Page 60: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

General File I/O Steps

1. Include the header file fstream in the program.

2. Declare file stream variables.

3. Associate the file stream variables with the input/output sources.

4. Open the file

5. Use the file stream variables with >>, <<, or other input/output functions.

6. Close the file.

Page 61: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Using Input/Output Files

stream - a sequence of characters

interactive (iostream)

• cin - input stream associated with keyboard.

• cout - output stream associated with display

file (fstream)

• ifstream - defines new input stream (normally associated with a file).

• ofstream - defines new output stream (normally associated with a

file).

Page 62: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Stream I/O Library Header Files

Note: There is no “.h” on standard header files : <fstream>

iostream -- contains basic information required for all

stream I/O operations

fstream -- contains information for performing file I/O

operations

Page 63: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

C++ streams//Add additional header files you use

#include <fstream>

int main ()

{ /* Declare file stream variables such as

the following */

ifstream fsIn;//input

ofstream fsOut; // output

fstream both //input & output

//Open the files

fsIn.open("prog1.txt"); //open the input file

fsOut.open("prog2.txt"); //open the output file

//Code for data manipulation

.

.

//Close files

fsIn.close();

fsOut.close();

return 0; }

Page 64: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Object and Member Functions

input_stream.open("numbers.txt“)

Page 65: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Open()

Opening a file associates a file stream variable declared in

the program with a physical file at the source, such as a

disk.

In the case of an input file:

the file must exist before the open statement executes.

If the file does not exist, the open statement fails and the input stream

enters the fail state

An output file does not have to exist before it is opened;

if the output file does not exist, the computer prepares an empty file

for output.

If the designated output file already exists, by default, the old

contents are erased when the file is opened.

Page 66: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Validate the file before trying to access

First method Second method

By checking the stream

variable;

If ( ! Mystream)

{

Cout << “Cannot open file.\n ”;

}

By using bool is_open() function.

If ( ! Mystream.is_open())

{

Cout << “File is not open.\n ”;

}

Page 67: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

File I/O Example: Open the file with validation

First Method (use the constructor) Second Method ( use Open function)

#include <fstream>

using namespace std;

int main()

{//declare and automatically open the file

ofstream outFile(“fout.txt");

// Open validation

if(! outFile) {

Cout << “Cannot open file.\n ”;

return 1;

}

return 0;

}

#include <fstream>

using namespace std;

int main()

{//declare output file variable

ofstream outFile;

// open an exist file fout.txt

outFile.open(“fout.txt”);

// Open validation

if(! outFile.is_open() ) {

Cout << “Cannot open file.\n ”;

return 1;

}

return 0;

}

Page 68: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

More Input File-Related Functions

ifstream fsin;

fsin.open(const char[] fname)

connects stream fsin to the external file fname.

fsin.get(char character)

extracts next character from the input stream fsin and places it

in the character variable character.

fsin.eof()

tests for the end-of-file condition.

Page 69: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

File I/O Example: ReadingRead char by char Read a line

#include <iostream>

#include <fstream>

int main()

{//Declare and open a text fileifstream openFile(“data.txt");

char ch;

//do until the end of file

while( ! OpenFile.eof() )

{OpenFile.get(ch); // get one character

cout << ch; // display the character

}

OpenFile.close(); // close the file

return 0;

}

#include <iostream>

#include <fstream>

#include <string>

int main()

{//Declare and open a text file

ifstream openFile("data.txt");

string line;

while(!openFile.eof())

{//fetch line from data.txt and put

it in a string

getline(openFile, line);

cout << line;

}

openFile.close(); // close the file

return 0;

}

Page 70: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

More Output File-Related Functions

ofstream fsOut;

fsOut.open(const char[] fname)

connects stream fsOut to the external file fname.

fsOut.put(char character)

inserts character character to the output stream fsOut.

fsOut.eof()

tests for the end-of-file condition.

Page 71: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

File I/O Example: WritingFirst Method (use the constructor) Second Method ( use Open function)

#include <fstream>

using namespace std;

int main()

{/* declare and automatically open the file*/

ofstream outFile("fout.txt");

//behave just like cout, put the word into the file

outFile << "Hello World!";

outFile.close();

return 0;}

#include <fstream>

using namespace std;

int main()

{// declare output file variableofstream outFile;

// open an exist file fout.txt

outFile.open("fout.txt”);

//behave just like cout, put the word into the file

outFile << "Hello World!";

outFile.close();

return 0;

}

Page 72: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

File Open ModeName Description

ios::in Open file to read

ios::out Open file to write

ios::app All the data you write, is put at the end of the file.

ios::trunc Deletes all previous content in the file. (empties

the file)

ios::nocreate If the file does not exists, opening it with the

open() function gets impossible.

ios::noreplace If the file exists, trying to open it with the open()

function, returns an error.

ios::binary Opens the file in binary mode.

Page 73: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

File Open Mode

#include <fstream>int main(void){ofstream outFile("file1.txt", ios::out);outFile << "That's new!\n";outFile.close();

Return 0;}

If you want to set more than one open mode, just use the OR

operator- |. This way:

ios::app | ios::binary

Page 74: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Summary of Input File-Related Functions

#include <fstream>

ifstream fsIn;

fsIn.open(const char[] fname)

connects stream fsIn to the external file fname.

fsIn.get(char& c)

extracts next character from the input stream fsIn and places it in the character variable c.

fsIn.eof()

tests for the end-of-file condition.

fsIn.close()

disconnects the stream and associated file.

fsIn >> c; //Behaves just like cin

Page 75: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Summary of Output File-Related Functions

#include <fstream>

ofstream fsOut;

fsOut.open(const char[] fname)

connects stream fsOut to the external file fname.

fsOut.put(char c)

inserts character c to the output stream fsOut.

fsOut.eof()

tests for the end-of-file condition.

fsOut.close()

disconnects the stream and associated file.

fsOut << c; //Behaves just like cout

Page 76: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

File format

In c++ files we (read from/ write to) them as a stream of

characters

What if I want to write or read numbers ?

Page 77: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Example writing to file

#include <iostream>

#include <fstream>

using namespace std;

void main()

{

ofstream outFile;

// open an exist file fout.txt

outFile.open("number.txt",ios::app);

if (!outFile.is_open())

{ cout << " problem with opening the file ";}

else

{

outFile <<200 <<endl ;

cout << "done writing" <<endl;

}

outFile.close();

}

Page 78: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Page 79: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Example Reading from file #include <iostream>

#include <fstream>

#include <string>

#include <sstream>

using namespace std;

void main()

{//Declare and open a text file

ifstream INFile("number.txt");

string line;

int total=0;

while(! INFile.eof())

{

getline(INFile, line);

//converting line string to int

stringstream(line) >> total;

cout << line <<endl;

cout <<total +1<<endl;

}

INFile.close(); // close the file

}

Page 80: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Page 81: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Programming Tips

Replacing numbers in your code with macros

- don’t use magic numbers directly

#define MAX_NAME_LEN 50;

char name[MAX_NAME_LEN];

Avoiding global variables

- modulation is more important

Giving variables and functions a nice name

- a meaning name

Don’t repeat your code

- make a subroutine/function

Don’t let the function body to exceed one screen

- hard to debug

Page 82: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Indenting your code (clearance)

if(expression)

{

if(expression)

{

……

}

}

Commenting your code

Don’t rush into coding. Plan first.

Printing out more debugging information

Using debugger (gdb)

Programming Tips

Page 83: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

C vs. C++

C++ is a superset of C

C++ has all the characteristics of C

Using g++ to compile your source code

Recommended IDE: Dev C++ (Newest version)

Page 84: C/C++ programming overviewmonet.skku.edu/wp-content/uploads/2019/03/C_CPP_Tutorial.pdf · C basics “Hello World" Program Data Types & Variables printf() Arithmetic & Logical Operations

Computer Networks

Books recommended

The C Programming Language, Brian Kernighan a

nd Dennis Ritchie. Second edition. Prentice-Hall,

1988. (C Bible)

The C++ Programming Language, Bjarne Stroustr

up. Third edition. Addison-Wesley, 1997. (C++ Bib

le)

Advanced Programming in the UNIX Environment,

W. Richard Stevens, Addison-Wesley, 1992. (APU

E)


Recommended