IPC144 Session 18 The C Programming Language

Preview:

DESCRIPTION

IPC144 Session 18 The C Programming Language. 1. Objectives List the file open and close functions, with their parameters and return values List the three modes to open a file in Explain the behaviour of the computer when opening existing and non-existent files under these modes - PowerPoint PPT Presentation

Citation preview

1

IPC144Session 18

The C Programming Language

2

Objectives

List the file open and close functions, with their parameters and return valuesList the three modes to open a file inExplain the behaviour of the computer when opening existing and non-existent files under these modesUse the file commands to read formatted and unformatted data from text filesTo define the three levels of scopeTo show the scope limits of variables within a C programShow the syntax to declare a structurePass structures to functions

3

The C Language

FilesA computer will loose the contents of memory when it is powered off

This can be rather inconvenient if there are megabytes of data that need to be entered every time the machine is powered up

The solution is to store the data on a media that does not easily loose its data, especially when powered off

The data is arranged on this media in FILES

4

The C Language

FilesA very common media used to store files is disks

There are two types of files: Binary and Text

Binary files consist of data that is in a format that the computer can easily read, but that people typically have a harder time understandinge.g. an executable file, a database file

Text files are a special case of binary filesText files consist of data that people can easily read

Text files contain lines of data that are terminated by a new-line character (the '\n' character we have seen)e.g. a C source code file

5

The C Language

FilesTry thinking of a file as a string

There will be a starting position and eventually an ending position that corresponds to the null terminator that we have seen in strings

The file equivalent to the strings null terminator is an End-Of-File marker (EOF)

When you are manipulating a string, you may have some sort of index into the string that points to the current character

Consider the following code that prints each character of a string on the same line:

6

The C Language

Files#include <stdio.h>#include <string.h>#define STRING_SIZE 50int main(void){ char aStringOfData[STRING_SIZE + 1]; int i; /* an index into the string */ strcpy(aStringOfData, “This is a test string”);

for (i = 0; i < strlen(aStringOfData); i = i + 1) { printf(“%c”, aStringOfData[i]); }

printf(“\n”); /* just to finish off the line */}

7

The C Language

Files#include <stdio.h>#include <string.h>#define STRING_SIZE 50#define STRING_EOF 0 /* end of string indicator for demo */int main(void){ char aStringOfData[STRING_SIZE + 1]; int i; /* an index into the string */ strcpy(aStringOfData, “This is a test string”);

i = 0; while (aStringOfData[i] != STRING_EOF) { printf(“%c”, aStringOfData[i]);

i = i + 1; }

printf(“\n”); /* just to finish off the line */}

8

The C Language

StreamsThere needs to be a way to create a connection between your program and a stream of data

This is accomplished by creating a pointer to the data stream

Oh no, more pointers

When defining a pointer to an int, we declare it as:int *ptrToInt;

We specify the data type (int) as well as the pointer variable ptrToInt

9

The C Language

StreamsWhen defining a pointer to a stream, we declare it as:FILE *ptrToStream;

e.g. FILE *fpInput;

Now that the pointer has been declared, how do we assign it to a stream?

We use the fopen function:

FILE *fopen(char *fileName, char *access);

10

The C Language

StreamsFILE *fopen(char *fileName, char *access);

This function returns: a pointer to the stream if it was successfully openedNULL if the stream was not successfully opened

The filename is either a pointer to a string or a literal passed to the functione.g.:

fp = fopen(“bank.txn”, “r”);OR

strcpy(fileName, “bank.txn”);fp = fopen(fileName, “r”);

The access string defines how the stream will be opened (more about access later)

11

The C Language

StreamsSome additional terminology for files and streams

When we compared a file to a string, we used used an index into the string (the variable 'i' for example) to keep track of where in the string we were

In the case of files there is also an 'index' that keeps track of where in the file we are- it is referred to as the 'file marker'

The operating system keeps track of the file marker

The file marker will range from the beginning of the file to the EOF (End-Of-File)

12

The C Language

StreamsSetting the file marker to the beginning of the file is like setting i = 0 when talking about strings

Setting the file marker to the end of the file (or to EOF) is like setting i = strlen(theString) when talking about strings

13

The C Language

StreamsA stream can be opened for READ or for WRITE or for APPEND

READThe file is opened for read only – the access string is “r”

The file must already exist- if the file does not exist NULL is returned by the fopen() function

If you attempt to WRITE data to this file, an error will be returned

If the file is opened successfully, the file marker is positioned at the beginning of the file

14

The C Language

WriteThe file is opened for write – the access string is “w”

If the file does not exist, it is created

If you attempt to READ data from this file, an error will be returned

If the file is opened successfully, the file marker is positioned at the beginning of the file

The successfully opened file will have all of its data deleted

15

The C Language

AppendThe file is opened for write – the access string is “a”

If the file does not exist, it is created

If you attempt to READ data from this file, an error will be returned

If the file is opened successfully, the file marker is positioned at the end of the file

In the case of a newly created file, the beginning of file and end of file are the same

16

The C Language

StreamsIn the cases above, there is no provision for UPDATING the contents of a text file

The reason is that if you were to replace a line of text in a file with a shorter line, you have no reliable way of deleting the left-over text

Conversely, if you wanted to replace a line of text with a longer line, you have no reliable way to insert space into the file to avoid overwriting the next line

17

The C Language

StreamsReplace the third line with ‘a shorter line’ (I used '<' to represent the new-line character, and ']' to represent the EOF)

this is a <long text file that<contains many lines of data<for your viewing pleasure]

You would get:

this is a <long text file that<a shorter line<lines of data<for your viewing pleasure]

18

The C Language

StreamsReplace the third line with ‘a much longer line for demonstration’

this is a <long text file that<contains many lines of data<for your viewing pleasure]

You would get:

this is a <long text file that<a much longer line for demonstration<viewing pleasure]

19

The C Language

StreamsNow that you have successfully opened a file for READ / WRITE / APPEND, how do you close it?

You use the fclose() function, the prototype is:

int fclose(FILE *filePointer);

If the fclose() function completes successfully, zero is returned

If fclose() completes unsuccessfully, EOF is returned

e.g.fclose(fp);

OR

result = fclose(fp);

20

The C Language

StreamsThis is probably a good time to point out that the C functions need to be CAREFULLY checked when using the return values

In some cases, such as fclose(), a zero is returned if the function completes SUCCESSFULLY - by definition C treats this value as FALSE

The return of zero is not necessarily wrong - it just means that there were zero errors encountered when running the function

You need to be careful how you use the return codes from functions

21

The C Language

StreamsBased on what has been discussed up to this point, write a C program that tests to see if a file called "bank.txn" exists. If it does not exist, create it. Remember to close your file at the end of the program.

22

The C Language

StreamsBased on what has been discussed up to this point, write a C program that tests to see if a file called "bank.txn" exists. If it does not exist, create it. Remember to close your file at the end of the program.

#include <stdio.h>void main(void){ FILE *fpBankFile;

fpBankFile = fopen(“bank.txn”, “r”); if (fpBankFile == NULL) { fpBankFile = fopen(“bank.txn”, “w”); if (fpBankFile == NULL) { printf(“Failed to Create bank.txn\n”); } }

fclose(fpBankFile);}

23

The C Language

StreamsHow do you read or write data to a file?

When writing formatted output to the screen, we used the printf() function

When writing unformatted output to the screen, we used the puts() function

When reading formatted input from the keyboard, we used the scanf() function

When reading unformatted input from the keyboard, we used the gets() function

Now that we are dealing with Files, we use variations of these functions

24

The C Language

StreamsThe fprintf() function is for printing formatted output to a file. Its function prototype is:

int fprintf(FILE *filePointer, char *format, ...);

As you can see, the only difference is the file pointer is now the first argument of the fprintf() function

If the function is successful, the number of characters printed is returned

If the function fails, EOF is returned

Although it may be not as meaningful to test the return code of the printf() function, the fprintf() should be tested as there is no other feedback that your program is running successfully

e.g.

fprintf(fp, “This is a number %d\n”, x);

25

The C Language

StreamsThe fputs() function is for printing unformatted output to a file. Its function prototype is:

int fputs(char *string, FILE *filePointer);

As you can see, the only difference is the file pointer is now the second argument of the fputs() function

If the function is successful, the number of characters printed is returned

If the function fails, EOF is returned

Again testing the results of the fputs() is a good idea

*puts() automatically appends a newline character at the end of the line*fputs() does not automatically append a newline character at the end of the line

e.g.fputs(mystr, fp);fputs(“Hello world\n”, fp);

26

The C Language

StreamsThe fscanf() function is for reading formatted input from a file. Its function prototype is:

int fscanf(FILE *filePointer, char *format, ...);

As you can see, the only difference is the file pointer is now the first argument of the fscanf() function

If the function is successful, the number of variables assigned to is returned

If the function fails, EOF is returned

e.g.fscanf(fp, “%d %d”, &vara, &qvar);

27

The C Language

StreamsThe fgets() function is for reading unformatted input from a file. Its function prototype is:

char *fgets(char *string, int n, FILE *filePointer);

There is an additional parameter, n, that is used to limit the number of characters that are to be read:

the computer will read n - 1 characters or until a '\n' character is detected - whichever occurs firstthis is useful to prevent a memory overrun by setting this value to the maximum size of the string- the computer will read n - 1 characters from the file, and set the nth character to '\0'if there is still data on the line, the next read will resume where previous read left off (the file marker is not advanced to the end of the line)

28

The C Language

Streamschar *fgets(char *string, int n, FILE *filePointer);

If the function completes successfully, a pointer to the string is returned

If the function does not complete successfully, NULL is returned

If the fgets() function reads a '\n' character, it is also stored

The fgets() function works better with strings than fscanf()

*gets() discards the newline character when it is read*fgets() does not discard the newline character – it is stored in the string

29

The C Language

StreamsThis is a sample of C code to open a file called test.txt for read and display its contents on the screen:

#include <stdio.h>#define BUFFER_SIZE 80int main(void){ FILE *fpInput; char fileData[BUFFER_SIZE + 1]; char *getStatus;

fpInput = fopen("test.txt", "r"); if (fpInput == NULL) { printf("Failed to Open Input File\n"); } else { getStatus = fgets(fileData, BUFFER_SIZE + 1, fpInput); while (getStatus != NULL) { printf("%s", fileData); getStatus = fgets(fileData, BUFFER_SIZE + 1, fpInput); } fclose(fpInput); }}

30

The C Language

StreamsThere are predefined file pointers within C

These pointers are created and opened to their respective streams when your program begins running

stdin - standard input - the keyboard

stdout - standard output - the screen

stderr - standard error - the screen

The scanf() and printf() functions can also be written:

fscanf(stdin, “%d\n”, myInt);fprintf(stdout, “%s\n”, myString);

31

The C Language

StreamsWrite a program that counts the number of lines in a file called "testdata.dat", as well as the number of characters (do not include the "\n" character in your count of characters)

32

The C Language

Streams#include <stdio.h>#include <string.h>#define BUFFER_SIZE 80

int main(void){ int lineCount; int charCount; char fileData[BUFFER_SIZE + 1]; char *readStatus; FILE *fpInput;

lineCount = 0; charCount = 0; fpInput = fopen("testdata.dat", "r"); if (fpInput == NULL) printf("Cannot open input file\n"); else { readStatus = fgets(fileData, BUFFER_SIZE + 1, fpInput); while (readStatus != NULL) { lineCount = lineCount + 1;; charCount = charCount + strlen(fileData) - 1; readStatus = fgets(fileData, BUFFER_SIZE + 1, fpInput); } printf("There are %d lines and %d characters\n", lineCount, charCount); fclose(fpInput); }}

33

Scope

34

The C Language

ScopeScope defines the extent to which a variable may be used in code. The hierarchy of scope is (from wide to narrow):

Global (or file level)Function prototypeBlock { }

This can become a seriously confusing mess if you start using the same variable names at each level of scope.

35

The C Language

Scope, continuedGlobal (or file level)

These variables are declared before (outside) of the main function:

#include <stdio.h>

int c;

int main(void){ printf("%d\n", c);}

They are visible (usable) by any part of the program (any function).

Generally speaking, global variables are considered a BAD thing from a style point of view. If at all possible, avoid using them.

36

The C Language

Scope, continuedFunction Prototype

These variables are declared as part of the declaration of a function:

#include <stdio.h>

void f1(int x);

int main(void){ int c; c = 5; f1(c);}

int f1(int c){ printf("C = %d\n", c);}

They are visible only to the function for which they are declared. When the function completes, these variables are destroyed.

37

The C Language

Scope, continuedBlock

These variables are declared between an opening and closing brace {...}:

#include <stdio.h>

int main(void){ int c; c = 5;

{ int i; i = 9; printf("i = %d\n", i); }}

They are visible only within the matching pair of braces. When the braces end, these variables are destroyed.

38

The C Language

Scope, continuedAssume we have a variable 'c' that is declared as a global variable.

It could be masked (hidden from view) by a variable called 'c' declared in a function declaration

Both of the above could be again hidden by a variable called 'c' declared in a block

C

C

C

39

The C Language

Scope, continued#include <stdio.h> int f1(int c);int f2(void); int c = 10;int main(void){ int c; for (c = 0; c < 5; c = c + 1) { int c; for (c = 5; c >= 0; c = c - 1) printf(" C = %d", c); printf("\n"); } printf("Block (main function) C = %d\n", c); f1(c); f2();} int f1(int c){ printf("Function prototype C = %d\n", c);} int f2(void){ printf("global C = %d\n", c);}

40

The C Language

Scope, continued C = 5 C = 4 C = 3 C = 2 C = 1 C = 0 C = 5 C = 4 C = 3 C = 2 C = 1 C = 0 C = 5 C = 4 C = 3 C = 2 C = 1 C = 0 C = 5 C = 4 C = 3 C = 2 C = 1 C = 0 C = 5 C = 4 C = 3 C = 2 C = 1 C = 0Block (main function) C = 5Function prototype C = 5global C = 10

41

Structures

42

The C Language

StructuresThere is a method in C to create a customized data type that allows you group a set of data types into one variable type called a structure.

The group of data types take on a single name, the name of the structure.

This is a convenient means to keep related data together.

It is self-documenting.

43

The C Language

StructuresAnatomy of a structure declaration:

struct structName { dataType varName;dataType varName;

. . .};

The list of elements - normal variable declarationsEnclosed in braces

The name for the collection / group / structureThe keyword to begin the declaration of a structure.

This can be considered a template- it is not a variable declaration (yet).

The template MUST exist at a level of scope that makes it visible to all instances.

44

The C Language

StructuresTo create an instance of the structure:

struct structName instanceName;

The name of the instance - the variable The template nameKeyword to define a structure

The syntax to reference an element of the structure.

instance.element

i.e.theStructure.a = 1;

45

The C Language

StructuresExample:

#include <stdio.h>#include <string.h>int main (void){ struct myStruct {int a; float b; char c; char str[10];};

struct myStruct theStruct; theStruct.a = 1; theStruct.b = 2.0; theStruct.c = '3'; strcpy(theStruct.str, "a string"); printf("the struct initially: a=%d b=%f c=%c str=%s\n", theStruct.a, theStruct.b, theStruct.c, theStruct.str); }

46

The C Language

Structures and FunctionsWhen passing structures from a module to a function, it must be passed by reference- the same as arrays are passed by reference.

The function call will include the address-of operator, the function declaration will include the indirection operator:

...myFunc(&theStruct);...

void myFunc(struct template *passedStruct){...}

Don't forget to declare the template at a higher level of scope.

47

The C Language

StructuresThe dereference operator that is embedded in the structure is the '->' operator.

instead of:

*myvar = x + y;

usetheStruct->element = x + y;

not *theStruct.element = x + y;

48

The C Language

Structures#include <stdio.h>#include <string.h>struct myStruct {int a; float b; char c; char str[10];}; void alters(struct myStruct *ts);int main (void){ struct myStruct theStruct; theStruct.a = 1; theStruct.b = 2.0; theStruct.c = '3'; strcpy(theStruct.str, "a string"); printf("the struct initially: a=%d b=%f c=%c str=%s\n", theStruct.a, theStruct.b, theStruct.c, theStruct.str); alters(&theStruct); printf("the struct after alter: a=%d b=%f c=%c str=%s\n", theStruct.a, theStruct.b, theStruct.c, theStruct.str);}void alters(struct myStruct *ts){ ts->a = 10; ts->b = 20.0; ts->c = '6'; strcpy(ts->str, "New String");}

49

The C Language

StructuresWhat if you needed to track vats of oil in a manufacturing system. Perhaps there will be a vat number, a total capacity for the vat, the current volume of oil in the vat and a description of the vat.

This could be stored in 4 arrays (int, double, double, string)

vatNum capacity volume description

50

The C Language

StructuresInstead of four arrays, of different data types and meanings, how about one array of structures?

vatNum

capacity

volume

description

51

The C Language

StructuresHow do we declare an array of structures?

Treat the structure instance declaration like any other data type we have seen:

int i[5];

struct template myinstance[5];

52

The C Language

StructuresTo reference a specific index within the array of structures, apply the [ ] to the STRUCTURE, not the element of the structure:

myinstance[i].a = x * y;

53

The C Language

StructuresFor example:

#include <stdio.h>#include <string.h>int main (void){ struct myStruct {int a; float b; char c; char str[10];};

struct myStruct theStruct[5]; int i;

for (i = 0; i < 5; i= i + 1) { theStruct[i].a = i; theStruct[i].b = 2.0 * i; theStruct[i].c = '0' + i; strcpy(theStruct[i].str, "a string"); }

for (i = 0; i < 5; i = i + 1) printf("the struct initially: a=%d b=%f c=%c str=%s\n", theStruct[i].a, theStruct[i].b, theStruct[i].c, theStruct[i].str);}

54

The C Language

StructuresNow things get really weird, when passing an array of structures to a function, we are already referencing the address of the array.

Recall:

int a[5];...

a[0] = 0;*a = 0;...

myFunc(a);...

void myFunc(int *a){}

55

The C Language

StructuresThe same happens with an array of structures:

struct template a[5];...

a[0].element1 = 0;...

myFunc(a);...

void myFunc(struct template *a){}

56

The C Language

Structuresvoid myFunc(struct template *a){}

The difference is when dealing with elements of the structure within the function.

Because the structure has already been dereferenced, the '->' operator is not required.

With the function, the elements can be accessed using the more familiar dot notation ('.').

57

The C Language

StructuresFor example:#include <stdio.h>#include <string.h>struct myStruct {int a; float b; char c; char str[10];}; void alters(struct myStruct *ts);int main (void){ struct myStruct theStruct[5]; int i; for (i = 0; i < 5; i= i + 1) { theStruct[i].a = i; theStruct[i].b = 2.0 * i; theStruct[i].c = '0' + i; strcpy(theStruct[i].str, "a string"); } for (i = 0; i < 5; i = i + 1) printf("the struct initially: a=%d b=%f c=%c str=%s\n", theStruct[i].a, theStruct[i].b, theStruct[i].c, theStruct[i].str); alters(theStruct); for (i = 0; i < 5; i = i + 1) printf("the struct after alter: a=%d b=%f c=%c str=%s\n", theStruct[i].a, theStruct[i].b, theStruct[i].c, theStruct[i].str);}

58

The C Language

Structures

void alters(struct myStruct *ts){ int i; for (i = 0; i < 5; i = i + 1) { ts[i].a = ts[i].a * 100; ts[i].b = ts[i].b * 1000.0; ts[i].c = ts[i].c - '0' + 'A'; strcpy(ts[i].str, "New String"); }}

Recommended