25
C Programming Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 1 C Programming Introduction and Basics C History Why use C? Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be: Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Data Bases Language Interpreters Utilities C provides Efficiency, high performance and high quality s/ws Flexibility and power Many high-level and low-level operations Stability and small size code

DESTI CProgramming

Embed Size (px)

Citation preview

Page 1: DESTI CProgramming

C Programming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 1

C ProgrammingIntroduction and Basics C History

Why use C? Mainly because it produces code that runs nearly as fast as code written in assembly

language. Some examples of the use of C might be:

– OperatingSystems

– LanguageCompilers

– Assemblers

– Text Editors

– Print Spoolers

– NetworkDrivers

– ModernPrograms

– Data Bases

– LanguageInterpreters

– Utilities

C provides Efficiency, high performance and high quality s/ws

Flexibility and power

Many high-level and low-level operations

Stability and small size code

Page 2: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 2

Provide functionality through rich set of function libraries

Gateway for other professional languages like C , C++, Java

SOFTWARE DEVELOPMENT METHOD Requirement Specification

Problem Definition

Analysis

Refine, Generalize, Decompose theproblem definition

Design

Develop Algorithm

Implementation

Write Code

Verification and Testing

Test and Debug the code

General Format• Preprocessor directives

• Global variable declaration

• Global Function declaration

• void main()

{Variable declarationFunction calls/statements

}• Function definition

Basics#include <stdio.h>void main(){

printf(“Hello, world!\n”);}

Pieces of C• Types and Variables

Definitions of data in memory• Expressions

Arithmetic, logical, and assignment operators in an infix Notation• Statements

Sequences of conditional, iteration, and branching instructions

Page 3: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 3

• Functions

Groups of statements and variables invoked recursively

Data Types• The Data Type families are

• Integer Family

• Float Family

• Integer Family

• Char

• Short

• Int

• long

• Float Family

• Float

• double

Storage Classes Extern

Static

Register

Auto

Type Casting Type casting is used when u want to convert the value of one data type to another

Type casting doesn’t change the actual value of the variable

Type casting is done using a cast operator.

C operators– Arithmetic operators

• Unary operators

• Binary operators

– Assignment operators

– Equalities and relationaloperators

– Logical operators

– Conditional operator

Arithmetic Operators• There are 2 types of arithmetic operators in C:

– unary operators - operators that require only one operand.

– binary operators - operators that require two operands.

Unary OperatorC Operation Operator ExamplePositive + a +=3Negative - b -=a

Page 4: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 4

Increment ++ i++Decrement -- i--

• The first assigns positive 3 to a

• The second assigns the negative value of a to b.

• i++ is equivalent to i = i + 1

• i-- is equivalent to i = i-1

PRE- / POST-Increment• It is also possible to use ++i and --i instead of i++ and i--

• However, the two forms have a slightly yet important difference.

Binary OperatorsC Operation Operator Example:Addition + a + 3Subtraction - a - 6Multiplication * a * bDivision / a / cModulus % a % x

• The division of variables of type int will always produce a variable of type int as theresult.

• You could only use modulus (%) operation on int variables.

Assignment Operators

Page 5: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 5

Precedence Rules• Precedence rules come into play when there is a mixed of arithmetic operators in one

statement. For example: x = 3 * a - ++b%3;

• The rules specify which of the operators will be evaluated first.

Precedence Operator Associatively Level1 (highest) () left to right2 unary right to left3 * / % left to right4 + - left to right5 (lowest) = += -= *= /= %= right to left

• Equality Operators:

Operator Example Meaning== x == y x is equal to y!= x != y x is not equal to y

• Relational Operators:

Operator Example Meaning> x > y x is greater than y< x < y x is less than y>= x >= y x is greater than or equal to y<= x <= y x is less than or equal to y

Logical Operators• Logical operators are useful when we want to test multiple conditions.

• There are 3 types of logical operators and they work the same way as the boolean AND,OR and NOT operators.

• && - Logical AND

– All the conditions must be true for the whole expression to be true.

– Example: if (a == 10 && b == 9 && d == 1)

means the if statement is only true when a == 10 and b == 9 and d == 1.• || - Logical OR

– The truth of one condition is enough to make the whole expression true.

– Example: if (a == 10 || b == 9 || d == 1)

means the if statement is true when either one of a, b or d has the rightvalue.

• ! - Logical NOT (also called logical negation)

– Reverse the meaning of a condition

Page 6: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 6

– Example: if (!(points > 90))

means if points not bigger than 90

Conditional Operator cont…Example 1:

if/else statement:if (total > 60)

grade = ‘P’else

grade = ‘F’;

conditional statement:total > 60 ? grade =

‘P’: grade = ‘F’;

ORgrade = total > 60 ?

‘P’: ‘F’;Conditional Operator cont…

• Example 2:

if/else statement:if (total > 60)

printf(“Passed!!\n”);else

printf(“Failed!!\n”);

Conditional Statement:printf(“%s!!\n”, total > 60? “Passed”: “Failed”);

Arrays in CDefinition – Array

• A collection of objects of the same type stored contiguously in memory under one name

• May be type of any kind of variable

• May even be collection of arrays!

• For ease of access to any member of array

• For passing to functions as a group

Examples• int A[10]

• An array of ten integers

• A[0], A[1], …, A[9]

• double B[20]

• An array of twenty long floating point numbers

Page 7: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 7

• B[0], B[1], …, B[19]

• Arrays of structs, unions, pointers, etc., are also allowed

• Array indexes always start at zero in C

• int C[]

• An array of an unknown number of integers (allowable in a parameter of afunction)

• C[0], C[1], …, C[max-1]

• int D[10][20]

• An array of ten rows, each of which is an array of twenty integers

• D[0][0], D[0][1], …, D[1][0], D[1][1], …, D[9][19]

• Not used so often as arrays of pointers

Array Element• May be used wherever a variable of the same type may be used

• In an expression (including arguments)

• On left side of assignment

• Examples:–

A[3] = x + y;x = y – A[3];z = sin(A[i]) + cos(B[j]);

• Generic form:–

• ArrayName[integer-expression]

• ArrayName[integer-expression] [integer-expression]

– Same type as the underlying type of the array

• Definition:– Array Index – the expression between the square brackets

• Array elements are commonly used in loops

NOTES• It is the programmer’s responsibility to avoid indexing off the end of an array

• Likely to corrupt data

Page 8: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 8

• May cause a segmentation fault

• Could expose system to a security hole!

• C does NOT check array bounds

• I.e., whether index points to an element within the array

• Might be high (beyond the end) or negative (before the array starts)

Declaring Arrays• Static or automatic

• Array size determined explicitly or implicitly

• Array size may be determined at run-time

• Automatic only

• Not in textbook

• Outside of any function – always static

Static Data Allocation

• Inside function or compound statement – usually automatic

Array Initialization• int A[5] = {2, 4, 8, 16, 32};

Page 9: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 9

• Static or automatic

• int B[20] = {2, 4, 8, 16, 32};

• Unspecified elements are guaranteed to be zero

• int C[4] = {2, 4, 8, 16, 32};

• Error — compiler detects too many initial values

• int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n};

• Automatically only; array initialized to expressions

• int E[n] = {1};

• gcc, C99, C++

• Dynamically allocated array (automatic only). Zeroth element initializedto 1; all other elements initialized to 0

Implicit Array Size Determination• int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

– Array is created with as many elements as initial values

• In this case, 12 elements

– Values must be compile-time constants (for static arrays)

– Values may be run-time expressions (for automatic arrays)

Getting Size of Implicit Array• sizeof operator – returns # of bytes of memory required by operand

• Examples:–

• sizeof (int) – # of bytes per int

• sizeof (float) – # of bytes per float

• sizeof days – # of bytes in array days (previous slide)

• # of elements in days = (sizeof days)/sizeof(int)

• Must be able to be determined at compile time

• Dynamically allocated arrays not supported

Page 10: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 10

Pointers in CWhat is a pointer?Syntax :

int *ptr;int *ptr;

• ptr is the name of our variable (just as k was the name of our integer variable).

• The '*' informs the compiler that we want a pointer variable, i.e. to set aside howevermany bytes is required to store an address in memory.

• The int says that we intend to use our pointer variable to store the address of an integer.Such a pointer is said to "point to" an integer.

• Now ptr has no value, that is we haven't stored an address in it in the above declaration.

• A pointer initialized in this manner is called a "null" pointer.

• ** The actual bit pattern used for a null pointer may or may not evaluate to zero since itdepends on the specific system on which the code is written.

NULL Macro and Pointer validation• To make the source code compatible between various compilers on various systems, a

macro is used to represent a null pointer.

• The macro goes under the name NULL.

• Setting the value of a pointer using the NULL macro, as with an assignment statementsuch as

ptr = NULL;guarantees that the pointer has become a null pointer.

• Validation of pointer can be done just as one can test for an integer value of zero,

if(k == 0),we can test for a null pointer using

if (ptr == NULL).• Be aware that "nul" is not the same as "NULL".

• The null refers to a zero as defined by the escape sequence '\0'. It occupies one byte ofmemory.

• NULL, on the other hand, is the name of the macro

How to use ptr?

Page 11: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 11

Pointer types andArrays

More on pointersPointers Arithmetic

• Address + Number= Address• Address - Number= Address

• Address++ = Address

Page 12: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 12

• Address-- = Address

• ++Address = Address

• --Address = Address

Illegal arithmetic• Address + Address=Illegal

• Address * Address=Illegal

• Address / Address=Illegal

• Address % Address=Illegal

Multidimensional Arrayschar [10];

• The name multi[5] is itself an array indicating that there are 5 elements each being anarray of 10 characters.

• Hence we have an array of 5 arrays of 10 characters each.

• In memory, it might look as if it had been formed by initializing 5 separate arrays.

multi[0] = {'0','1','2','3','4','5','6','7','8','9'}multi[1] = {'a','b','c','d','e','f','g','h','i','j'}

multi[2] = {'A','B','C','D','E','F','G','H','I','J'}multi[3] = {'9','8','7','6','5','4','3','2','1','0'}multi[4] = {'J','I','H','G','F','E','D','C','B','A'}

Accessing Multidimensional array content

• Individual elements might be addressable using syntax such as:

multi[0][3] = '3‘multi[1][7] = 'h'multi[4][0] = 'J‘

Page 13: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 13

• multi + 1 is the address of the 'a' in the 2nd row. It adds 10, the number of columns, toget this location.

• If we were dealing with integers and an array with the same dimension the compilerwould add 10*sizeof(int).

• Thus, the address of the 9 in the 4th row would be &multi[3][0] or *(multi + 3) inpointer notation.

• To get to the content of the 2nd element in the 4th row we add 1 to this address anddereference the result as.

*(*(multi + 3) + 1)• With a little thought we can see that:

*(*(multi + row) + col)and

multi[row][col]yield the same results.

*(*(multi + row)+col) Vs multi[row][col]• To evaluate either expression, a total of 5 values must be known:

– The address of the first element of the array, which is returned by the expressionmulti, i.e., the name of the array.

– The size of the type of the elements of the array, in this case sizeof(int).

– The 2nd dimension of the array.

– The specific index value for the first dimension, row in this case.

– The specific index value for the second dimension, col in this case.

Strings in CCharacters in C char is a one-byte data type capable of holding a character

• Treated as an arithmetic integer type

• (Usually) unsigned

• May be used in arithmetic expressions

• Add, subtract, multiply, divide, etc.

• Character constants

• 'a', 'b', 'c', …'z', '0', '1', … '9', '+', '-', '=', '!', '~', etc, '\n', '\t', '\0', etc.

Page 14: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 14

• A-Z, a-z, 0-9 are in order, so that arithmetic can be done

Strings in C• Definition:– A string is a character array ending in '\0' — i.e.,

– char s[256];

– char t[] = "This is an initialized string!";

– char *u = "This is another string!";

– String constants are in double quotes

• May contain any characters

• Including \" and \' — see p. 38, 193 of K&R

• String constants may not span lines

• However, they may be concatenated — e.g.,

"Hello, " "World!\n" is the same as "Hello, World!\n"• Let

– char *u = "This is another string!";

• Then

– u[0] == 'T'u[1] == 'h'u[2] == 'i'…u[21] == 'g'u[22] == '!'u[23] == '\0'

Support for Strings in C• Most string manipulation is done through functions in <string.h>

• String functions depend upon final '\0'

• So you don’t have to count the characters!

• Examples:–

– int strlen(char *s) – returns length of string

• Excluding final '\0'

Page 15: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 15

– char* strcpy(char *s, char *ct) – Copies string ct to string s, return s

• s must be big enough to hold contents of ct

• ct may be smaller than s

– int strcmp(char *s, char *t)

• lexically compares s and t, returns <0 if s < t, >0 ifs > t, zero if s and t are identical

– char* strcat(char *s, char *ct)

• Concatenates string ct to onto end of string s, returns s

• s must be big enough to hold contents of both strings!

Other string functions– strchr(), strrchr(), strspn(), strcspn() strpbrk(), strstr(), strtok(), …

Definition — The Heap• A region of memory provided by most operating systems for allocating storage not in

Last in, First out discipline

• I.e., not a stack

• Must be explicitly allocated and released

• May be accessed only with pointers

• Remember, an array is equivalent to a pointer

• Many hazards to the C programmer

Static Data Allocation

Page 16: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 16

Allocating Memory in The Heap• See <stdlib.h>

void *malloc(size);void free(void *ptr);void *calloc(size_t nmemb, size_t size);

• malloc() — allocates size bytes of memory from the heap and returns a pointer to it.

• NULL pointer if allocation fails for any reason

• free() — returns the chunk of memory pointed to by ptr

• Must have been allocated by malloc or calloc

Notes• calloc() is just a variant of malloc()

• malloc() is analogous to new in C++ and Java

• new in C++ actually calls malloc()

• free() is analogous to delete in C++

• delete in C++ actually calls free()

• Java does not have delete — uses garbage collection to recover memoryno longer in use

Definition – Memory Leak• The steady loss of available memory due to forgetting to free() everything that was

malloc’ed.

• Bug-a-boo of most large C and C++ programs

• If you “forget” the value of a pointer to a piece of malloc’ed memory, there is no way tofind it again!

• Killing the program frees all memory!

Functions in C– Modularize a program

– Benefits of functions

– Divide and conquer

• Manageable program development

Page 17: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 17

– Software reusability

• Use existing functions as building blocks for new programs

• Abstraction - hide internal details (library functions)

– Avoid code repetition

Library function:The library function is not required to be written by us.

Eg:printfscanfstrcmpstrlen

mallocfreeetc..

User defines function: This function has to be developed by the user at the time of writing a program.

Eg: main()‘main’ is specially used function in C. Every program must have main

function to indicate, where the program begins its execution. When a program is largeand complex then the result of debugging testing and maintaining becomes difficult.

The 3 aspects of functions are:1. The Function Declaration also called Prototype

2. The function Definition

Page 18: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 18

3. The Function Invocation or calling StatementFunction Declaration

• In C user- written functions should normally be declared prior to its use to allow compilerto perform type checking on arguments used in its call statement.

• The general form is:

• Return_data_type function_name (data_type Var_name, …..);

• Function name: this is the name given to the function. It follows the same namingconvention as that of any valid variable in C.

• Return data type: this specifies the type of data given back to the calling construct.

• Data type list: this list specifies the data type of each variables, the values of which areexpected to be transmitted to the function. These variables are known as formalparameters.

• It is possible not to declare functions prior to the use but the error checking will not beperformed.

• ; is required at the end of function declaration.

• E.g. int FindMax(int x, int y);

Function Definition The collection of program statements that does specific tasks done by the function is

called the function definition.

It consist of function header:

and function body.

variables defined inside the function are local variables

Parameters to a functions can be considered as local variables

Function Invocation or function call• The function is called from the main()

• The function can in turn call another function.

• The function call statements invoke the function, which means the program controlpasses to that function. Once the function completes its task, the program control ispassed back to the calling environment.

• Av = getAverage(10, 20, 30);

Page 19: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 19

• Av = getAverage(v1, v2,v3);

• Av =getAverage(10,v1,v2);

• var_name=function_name(var1, var2,..);

Classification of Functions• Functions that will not take any arguments and also returns none

• Functions that will not take any arguments and returns some value

• Functions that takes one or more arguments but returns none

• Functions that take one or more arguments and returns some value

NOTES• The function name and the type and number of arguments must match with that of the

function declaration statement and the header of the function definition.

• Arguments present in the form of expression are evaluated and converted to the type offormal parameters at the beginning of the body of the function.

Passing of arguments to the function1. Call by value or pass by value:

1. When arguments are passed by values this means that local copies of the values ofthe arguments are passed to the function.

2. Call by reference or pass by reference.

1. The address of the variable is passed as value of parameters to the function.

Passing arrays to functions• Arrays can also be the arguments of function

• Only the base address of the array is passed to the function

• Hence the passing of arguments is done by reference.

• When arrays are passed as arguments then actual contents of the arrays is altered.

Structures and UnionsDefinition — Structure

• A collection of one or more variables, typically of different types, grouped together undera single name for convenient handling

• Known as struct in C and C++

Page 20: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 20

Struct• Defines a new type

• I.e., a new kind of data type that compiler regards as a unit

• E.g.,

struct motor {float volts; //voltage of the motorfloat amps; //amperage of the motorint phases; //# of phases of the motorfloat rpm; //rotational speed of motor}; //struct motor

Declaring struct variablesstruct motor p, q, r;

• Declares and sets aside storage for three variables – p, q, and r – each oftype struct motor

struct motor M[25];• Declares a 25-element array of struct motor; allocates 25 units of storage,

each one big enough to hold the data of one motor

struct motor *m;• Declares a pointer to an object of type struct motor

Accessing Members of a struct• Let

struct motor p;struct motor q[10];

• Then

p.volts — is the voltagep.amps — is the amperagep.phases — is the number of phasesp.rpm — is the rotational speedq[i].volts — is the voltage of the ith motorq[i].rpm — is the speed of the ith motorAccessing Members of a struct (continued)

• Let

struct motor *p;• Then

(*p).volts — is the voltage of the motor pointedto by p

Page 21: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 21

(*p).phases — is the number of phases of themotor pointed to by p

• The (*p).member notation is a nuisance

• Clumsy to type; need to match ( )

• Too many keystrokes

• This construct is so widely used that a special notation was invented, i.e.,

– p->member, where p is a pointer to the structure

Previous Example Becomes …• Let

• struct motor *p;

• Then

p -> volts — is the voltage of the motor pointed to by pp -> phases — is the number of phases of the motor pointed to by p

Operations on struct• Copy/assign

struct motor p, q;p = q;

• Get address

struct motor p;

struct motor *ss = &p;

• Access members

p.volts;s -> amps;

• Remember:–

– Passing an argument by value is an instance of copying or assignment

– Passing a return value from a function to the caller is an instance of copying orassignment

Initialization of a struct• Let struct motor {

float volts;float amps;int phases;float rpm;

}; //struct motor

Page 22: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 22

• Thenstruct motor m = {208, 20, 3, 1800};

initializes the struct

Typedef• Definition:– a typedef is a way of renaming a type

• E.g.,

typedef struct motor Motor;Motor m, n;Motor *p, r[25];Motor function(const Motor m; …);

• typedef may be used to rename any type

– Convenience in naming

– Clarifies purpose of the type

– Cleaner, more readable code

– Portability across platforms

• E.g.,

– typedef char *String;

• E.g.,

– typedef int size_t;

– typedef long int32;

– typedef long long int64;

Unions• A union is like a struct, but only one of its members is stored, not all

• I.e., a single variable may hold different types at different times

• Storage is enough to hold largest member

• Members are overlaid on top of each other

Union SyntaxUnion [union-type-name]{typevariable-names;typevariable-names;…...

}[unionvariable];

Page 23: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 23

Difference between Structure & Union

Structure Union

A structure allocates the total size of all elements in it. A union only allocates as much memory as its largestelement(member) requires.

Members inside a structure are always stored inseparate memory locations throughout the life time andscope of the entire structure.

The union will store one and only one actual value forone element at a time.

Manipulations of one member will not affect the valuesof any of the others in any way unless they are operatedon in code to do so.

If another element is stored before the first is retrieved,the first stored value is lost.

The keyword struct is used to declare a structure The keyword union is used to declare an union.

All data members in a structure are active at time Only one data member is active at a time

• unions are used much less frequently than structs — mostly

• in the inner details of operating system

• in device drivers

• in embedded systems where you have to access registers definedby the hardware

FILE OPERATORSWhat 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 remainintact when a computer shuts down.

When a computer reads a file, it copies the file from the storage device tomemory; when it writes to a file, it transfers data from memory to the storagedevice.

Buffers A buffer is a “special work area” that holds data as the computer transfers them

to/from memory.

Buffers help to synchronize data the physical devices with the program.

Page 24: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 24

The physical requirements of the devices can deliver more data for input than aprogram can use at any one time. The buffer handles the overflow data until aprogram can use it.

Moreover, the buffer also holds data until it is efficient to write that data to thestorage device for output.

File Information Table A program requires several pieces of information about a file, including the name

the OS uses for it, the position of the current character, etc.

C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.

Streams• In C, we input/output data using streams. We can associate a stream with a device

(i.e. the terminal) or with a file.

• C supports two types of files

– Text Stream Files

– Binary Stream Files

Text Streams & Binary Streams Text streams consist of sequential characters divided into lines. Each line

terminates with the newline character (\n).

Binary streams consist of data values such as integers, floats or complex datatypes, “using their memory representation.”

Files & Streams A file is an “independent entity” with a name recorded by the operating system.

A stream is created by a program.

To work with a file, we must associate our stream name with the file namerecorded by the OS.

Steps in Processing a File1. Create the stream via a pointer variable using the FILE structure:

FILE* spData;

2. Open the file, associating the stream name with the file name.

3. Read or write the data.

4. Close the file

Page 25: DESTI CProgramming

Email: [email protected] Call: +91-800 822 5556, +91-800 833 5556 www.desti-group.com Page 25

System-Created Streams C automatically creates three streams that it opens and closes automatically for us

in order to communicate with the terminal:

• stdin stdout stderr

We cannot re-declare these streams in our programs.

File Open The file open function (fopen) serves two purposes:

– It makes the connection between the physical file and the stream.

– It creates “a program file structure to store the information” C needs toprocess the file.

Syntax:fopen(“filename”, “mode”);

More On fopen The file mode tells C how the program will use the file.

The filename indicates the system name and location for the file.

We assign the return value of fopen to our pointer variable:

spData = fopen(“MYFILE.DAT”, “w”);spData = fopen(“A:\\MYFILE.DAT”, “w”);File OpenModes

Closing a File• When we finish with a mode, we need to close the file before ending the program

or beginning another mode with that same file.

• To close a file, we use fclose and the pointer variable:fclose(spData);