240 likes | 313 Views
More On File IO. What is a File. A file is a package of information with a name attached to it. Files are used for various purposes: Files can record data , such as text or numbers.
E N D
What is a File • A file is a package of information with a name attached to it. • Files are used for various purposes: • Files can record data, such as text or numbers. • Some files record ways to perform various processing procedures on data. These are referred to as programs or commands. • Conceptually, a file is a sequence of characters, which resides somewhere on a disk.
Access Files • To access a file • Open • Read / Write • Close Read/write A data file Your c code
Methods • FILE* - structure for holding file • fopen • Read - getc • Write - putc • fclose
More reading - fscanf • Read like scanf does, just from a file • Takes an additional argument which is the file to read from • fscanf(inFilePtr, “%f”, &fv); • Returns number of arguments read and assigned or EOF if end of file is reached before anything is assigned
More writing - fprintf • Writes like printf does, just to a file • Takes an additional argument which is the file to print to • fprintf(outFilePtr, “This is how its done\n”);
Reading lines- fgets • fgets(buffer, n, filePtr) • buffer is where the line is stored • n is the max number of characters to be stored in buffer • filePtr is where to read from • Reads characters from file and stores them in buffer • Stops when ‘\n’ is reached or when n-1 characters have been read • Returns NULL on failure and buffer on success
Writing strings - fputs • fputs(buffer, filePtr) • Writes the contents of buffer to filePtr • Writes each character until the ‘\0’ is reached • Does not write ‘\0’ to the file
Constant Files • Three files are automatically opened in every c program • Identified by constant file pointers defined in <stdio.h> • stdin: standard input (console input from user) • scanf • stdout: output to the terminal • printf • stderr: normally outputs to terminal but different file
Constant Files (cont) • scanf(…) = fscanf(stdin, …) • printf(…) = fprintf(stdout, …) • getc(stdin) = getchar() • putc(stdout) = putchar() • fgets(buffer, n, stdin) ≈ gets(buffer) • fgets includes ‘\n’ at the end of buffer • fputs(buffer, stdout) ≈ puts(buffer) • fputs does not append ‘\n’ to end of buffer • puts appends new line to end of buffer
Structures • Structures in C allows us to represent a collection of variables (possibly of different types) under a single name. • It allows us to create record style data with various fields. • More generally, it allows us to model real-world entities. • An entity is something that has a distinct, seperate existence. • An entity has a set of attributes that describes it. • Any object in the real-world can be modeled as an entity. • A book is an entity that can be distinguished from say a car.
Structure – Declaring • A collection of values (members) – type declaration struct struct_name { type1 data_member1; type2 data_member2; …; typeN data_memberN; }; • Declare a structure variable – instance declaration • struct struct_name instance_name;
Declarations • Three ways • struct date{ • int day; • char month[10]; • int year; • }; • struct date today; • typedef struct{ • int day; • char month[10]; • int year; • } date; • date today; • struct{ • int day; • char month[10]; • int year; • } today;
Initialization struct { int day; char month[10]; int year; } today = {15, “June”, 2007}; typedef struct { int day; char month[10]; int year; } date; date today = {15, “June”, 2007}; • struct date{ • int day; • char month[10]; • int year; • }; • struct date today = {15, “June”, 2007};
How to use .day • To access the members in the structure • specify the variable name, followed by a period and the member name • today.day = 15; • today.year = 2007; • today.month[0]=‘J’; • today.month[1]=‘u’; • today.month[2]=‘n’; • today.month[3]=‘e’; • today.month[4]=‘\0’; • OR • today.day = 15; • today.year = 2007; • today.month=“June”; today .month .year
How to use structure – cont. • Structure variable can be passed as a parameter to a function. • Structure variable can be returned from a function • Can have arrays of structures, and structures containing arrays or other structures. • struct date list_of_days[10]; • struct journalEntry { int location; struct date when; char entry[1000]; };
Arrays of Structures • Just like integer arrays and character arrays, we can also have an array of structures. • An integer array allows us to associate a list of numbers with a single variable name. • Similarly, an array of structures is a way of associating a a number of structures (entities) with a single variable name. • A class of students
Define the structure first • Before we can create an array of book structures, we need to declare a structure to represent a book typedef struct { char title[50]; char author[30]; float price; }book; • Usually placed at beginning of program (after #include statements)
Arrays of Structures • To represent a collection of books, we can create an array of book structures. • The declaration is identical to how we would declare an integer array. • For example, if we want to represent a set of 10 numbers we would declare: • int numbers[10]; • Similarly, to declare an array that can hold 10 book structures: • book library[10]; • Here library is the variable that we use to refer to the entire array. • Each element in the array is of type book. • Notice that book is a structure type that we declared earlier using the typedef struct syntax.
Accessing elements • Recall accessing elements in an array of ints • numbers[0] first number in the array • numbers[7] eighth number in the array • can manipulate numbers[ i ] just like a regular int for a valid index i • Access it, assign to it, multiply by it, add to it, etc • Same is true for an array of structs • library[0] first book in the array • library[5] sixth book in the array • Then you can just add . to the end and whatever field you want to access • libray[2].author gets the author of the third book in the array
Accessing elements (cnt) • Individual elements in the array can be accessed using the subscript operator []. • Consider the code snippet that initializes the first book element, located at index position 0 in the array: • strcpy (b[0].title, "Harry Potter and the Sorcerer's Stone"); • strcpy (b[0].author, "J.K.Rowling"); • b[0].price = 14.99; • Similary, we can initalize the remaining book elements: b[1], b[2], b[3] and so on till the last book element at b[9].
Iterating over the array • Assume we have initialized all the book elements for the array b. Our goal is to now print the details of each book element in the array. • This can be done by using a loop: int i = 0; while (i < 10) { // display book information printf ("Title: %s \n", b[i].title); printf ("Author: %s \n", b[i].author); printf ("Price: %f \n", b[i].price); }
Passing Structures to a Function • A structure variable or structure array has similar properties like an integer variable or integer array. • A function that receives an integer array along with the number of elements in the array will be declared as: • void function (int numbers[], int sz); • Similarly, a function that receives a book array along with the number of elements in the array can be declared as: • void function (book library[], int sz);