1 IPC144 Session 18 The C Programming Language. 2 Objectives List the file open and close functions, with their parameters and return values List the.

Slides:



Advertisements
Similar presentations
File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
Advertisements

I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Introduction to C Programming
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
FILES Files types and operations. Files Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
A First Book of ANSI C Fourth Edition Chapter 10 Data Files.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
Chapter 18 I/O in C.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Files A collection of related data treated as a unit. Two types Text
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
File I/O.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE1320 Files in C Dr. Sajib Datta
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
File Input and Output.
File Handling.
Fundamental of Programming (C)
Programming in C Input / Output.
Files.
ICS103: Programming in C 6: Pointers and Modular Programming
Files Chapter 8.
Presentation transcript:

1 IPC144 Session 18 The C Programming Language

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

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

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

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:

6 The C Language Files #include #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 */ }

7 The C Language Files #include #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 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

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

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)‏

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)‏

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

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

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

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

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

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]

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 ]

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

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

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.

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 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 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

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

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

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

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)‏

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

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

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

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)‏

32 The C Language Streams #include #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 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.

35 The C Language Scope, continued Global (or file level)‏ These variables are declared before (outside) of the main function: #include 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, continued Function Prototype These variables are declared as part of the declaration of a function: #include 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, continued Block These variables are declared between an opening and closing brace {...}: #include 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, 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

39 The C Language Scope, continued #include 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 Block (main function) C = 5 Function prototype C = 5 global C = 10

41 Structures

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.

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.

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;

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

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;

48 The C Language Structures #include 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 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 volumedescription

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

51 The C Language Structures How 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 Structures To 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 Structures For example: #include 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 Structures Now 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 Structures The 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 Structures void 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 Structures For example: #include 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 * ; ts[i].c = ts[i].c - '0' + 'A'; strcpy(ts[i].str, "New String"); }