1 / 58

IPC144 Session 18 The C Programming Language

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

Download Presentation

IPC144 Session 18 The C Programming Language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IPC144 Session 18 The C Programming Language 1

  2. 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 • Use the file commands to read formatted and unformatted data from text files • To define the three levels of scope • To show the scope limits of variables within a C program • Show the syntax to declare a structure • Pass structures to functions 2

  3. The C Language Files A 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 3

  4. The C Language • Files • A 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 understanding • e.g. an executable file, a database file • Text files are a special case of binary files • Text 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 4

  5. The C Language Files Try 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: 5

  6. The C Language Files #include <stdio.h> #include <string.h> #define STRING_SIZE 50 int 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 */ } 6

  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 */ } 7

  8. The C Language Streams There 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 8

  9. The C Language Streams When 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); 9

  10. The C Language • Streams • FILE *fopen(char *fileName, char *access); • This function returns: • a pointer to the stream if it was successfully opened • NULL if the stream was not successfully opened • The filename is either a pointer to a string or a literal passed to the function • e.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)‏ 10

  11. The C Language Streams Some 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)‏ 11

  12. The C Language Streams Setting 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 12

  13. The C Language Streams A stream can be opened for READ or for WRITE or for APPEND READ The 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 13

  14. The C Language Write The 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 14

  15. The C Language Append The 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 15

  16. The C Language Streams In 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 16

  17. The C Language Streams Replace 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] 17

  18. The C Language Streams Replace 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] 18

  19. The C Language Streams Now 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); 19

  20. The C Language Streams This 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 20

  21. The C Language Streams Based 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. 21

  22. The C Language Streams Based 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); } 22

  23. The C Language Streams How 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 23

  24. The C Language Streams The 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); 24

  25. The C Language Streams The 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); 25

  26. The C Language Streams The 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); 26

  27. The C Language • Streams • The 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 first • this 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)‏ 27

  28. The C Language Streams char *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 28

  29. The C Language Streams This 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 80 int 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); } } 29

  30. The C Language Streams There 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); 30

  31. The C Language Streams Write 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)‏ 31

  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); } } 32

  33. Scope 33

  34. The C Language Scope Scope 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 prototype Block { } This can become a seriously confusing mess if you start using the same variable names at each level of scope. 34

  35. The C Language Scope, continued Global (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. 35

  36. The C Language Scope, continued Function 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. 36

  37. The C Language Scope, continued Block 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. 37

  38. The C Language Scope, continued Assume 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 38

  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); } 39

  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 = 0 Block (main function) C = 5 Function prototype C = 5 global C = 10 40

  41. Structures 41

  42. The C Language Structures There 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. 42

  43. The C Language Structures Anatomy of a structure declaration: struct structName { dataType varName; dataType varName; . . . }; The list of elements - normal variable declarations Enclosed in braces The name for the collection / group / structure The 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. 43

  44. The C Language Structures To create an instance of the structure: struct structName instanceName; The name of the instance - the variable The template name Keyword to define a structure The syntax to reference an element of the structure. instance.element i.e. theStructure.a = 1; 44

  45. The C Language Structures Example: #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); } 45

  46. The C Language Structures and Functions When 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. 46

  47. The C Language Structures The dereference operator that is embedded in the structure is the '->' operator. instead of: *myvar = x + y; use theStruct->element = x + y; not *theStruct.element = x + y; 47

  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"); } 48

  49. The C Language Structures What 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 49

  50. The C Language vatNum capacity volume description Structures Instead of four arrays, of different data types and meanings, how about one array of structures? 50

More Related