more on file io

24
CGS 3460 More On File IO

Upload: caia

Post on 08-Jan-2016

18 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: More On File IO

     

CGS 3460

More On File IOMore On File IO

Page 2: More On File IO

     

CGS 3460

What is a FileWhat 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.

Page 3: More On File IO

     

CGS 3460

Access FilesAccess Files

To access a file Open Read / Write Close

Your c codeA data file

Read/write

Page 4: More On File IO

     

CGS 3460

MethodsMethods

FILE* - structure for holding file fopen Read - getc Write - putc fclose

Page 5: More On File IO

     

CGS 3460

More reading - fscanfMore 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

Page 6: More On File IO

     

CGS 3460

More writing - fprintfMore 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”);

Page 7: More On File IO

     

CGS 3460

Reading lines- fgetsReading 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

Page 8: More On File IO

     

CGS 3460

Writing strings - fputsWriting 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

Page 9: More On File IO

     

CGS 3460

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

Page 10: More On File IO

     

CGS 3460

Constant Files (cont)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

Page 11: More On File IO

     

CGS 3460

Arrays of StructuresArrays of Structures

Page 12: More On File IO

     

CGS 3460

StructuresStructures

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.

Page 13: More On File IO

     

CGS 3460

Structure – DeclaringStructure – Declaring

A collection of values (members) – type declarationstruct struct_name

{

type1 data_member1;

type2 data_member2;

…;

typeN data_memberN;

}; Declare a structure variable – instance declaration

struct struct_name instance_name;

Page 14: More On File IO

     

CGS 3460

DeclarationsDeclarations

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;

Page 15: More On File IO

     

CGS 3460

InitializationInitialization

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

Page 16: More On File IO

     

CGS 3460

How to useHow to use 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”;

15

‘J’

‘u’

‘n’

‘e’

‘\0’

2007

.month

.day

.year

today

Page 17: More On File IO

     

CGS 3460

How to use structure – cont.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];

};

Page 18: More On File IO

     

CGS 3460

Arrays of StructuresArrays 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

Page 19: More On File IO

     

CGS 3460

Define the structure firstDefine 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)

Page 20: More On File IO

     

CGS 3460

Arrays of StructuresArrays 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.

Page 21: More On File IO

     

CGS 3460

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

Page 22: More On File IO

     

CGS 3460

Accessing elements (cnt)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].

Page 23: More On File IO

     

CGS 3460

Iterating over the arrayIterating 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);

}

Page 24: More On File IO

     

CGS 3460

Passing Structures to a FunctionPassing 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);