Download presentation
Presentation is loading. Please wait.
1
UNIT-IV: Structures Objectives
To introduce the structure, union and enumerated types. To create and use structures in programs. To be able to use unions in programs. To use enumerated types in programs. 1
2
Structure A structure is a collection of related elements grouped together under a single name. Elements in a structure can be of same or different types. A smallest element in a structure is called a field. The difference between an array and a structure is that all elements in an array must be of same type, while the elements in a structure can be of the same or different types. Example: Structure 2
3
The Type Definition typedef
A typedef , gives a name to a datatype by creating a new type that can then be used anywhere a type is permitted typedef identifier is traditionally coded in upper case. typedef int LENGTH; One of the more common uses of the type definition is with complex declarations. char* stringPtrAry[20] A typedef is a way of renaming a type Syntex typedef struct motor Motor; Motor m, n; Motor *p, r[25]; Motor function(const Motor m; …); Good morning Ladies and Gentlemen. Welcome to this talk on “Pointers in C,” presented by Michael. E.g., typedef, lets you leave out the word “struct”
4
The Type Definition typedef may be used to rename any type
Clarifies purpose of the type Cleaner, more readable code Portability across platforms Convenience in naming Example typedef char *String; typedef int size_t; typedef long int32; typedef long long int64; We can use the typedef statement to re-define one of C’s standard data types (int, float, etc.). Example: Type-definition format
5
The Enumerated Type “The enumerated type is a user-defined type based on the standard integer type.” We give each value in an enumerated type an identifier that we call an enumeration constant, which we can use as a symbolic name. Declaring an Enumerated Type To declare an enumerated type, declare its identifier and its values. Operations are same as for integers because it is derived from the integer type. Syntax: enum typeName { identifierList }; If values to the members of the identifier list are not assigned, C will assign values, beginning at 0.
6
Enumerate Types Example
Syntax: enum typeName { identifierList }; Example: enum color { RED, BLUE, GREEN, WHITE }; In this example, C assigns the member RED the value of 0.
7
Creating Variables from Enumerations
Once we’ve declared an enumeration, we can create variables from them. We can use those variables anywhere in a program where we could also use integers.
8
Operations on Enumerated Types
Assigning values to Enumerated Types Enumerated variables can hold only declared variables for the type. Example: Defines a colour variable and uses it in several application. enum color x; enum color y; enum color z; x = BLUE; y = WHITE; //Error - PURPLE not defined. z = PURPLE; x = y; z = y;
9
Operations on Enumerated Types
Conversion We can both implicitly and explicitly cast enumerations. Although we can implicitly cast an enumeration to an integer, if we try to implicitly caste an integer to an enumeration, we will get a compile error. To correctly caste an integer: enum color y; y = (enum color)2;
10
Operations on Enumerated Types
Initialzing Enumerated types can be initialized by assigning an integer value to list members: enum color { RED = 1, BLUE = 2, GREEN = 3, WHITE = 15 }; If we want to assign sequential values, beginning with a specified value, we only need to specify the first value: enum color { JAN = 1, FEB, MAR, … NOV DEC }; Turbo c enum1.c with error simulation
11
Operations on Enumerated Types
Input/Output Enumerations are derived integers. They must be input/output as if they were integers. Example: enum months month1; enum months month1; scanf(“%d %d”, &month1, &month2); printf(“%d %d”, month1, month2);
12
Structure Type Declaration
C has two ways to declare a structure: Tagged Structure 2) Type-defined Structures Tagged Structure Example: A tagged structure starts with a keyword struct. The second element in the declaration is the tag, an identifier for the structure. If the structure is concluded with a semicolon after the closing brace, no variables are defined the structure is simply a type template with no associated storage.
13
Structure Type Declaration
Type Declaration with type-def A powerful way to declare a structure Format of typedef Type-defined structure differs from the tagged structure in two ways. 1. The keyword, typedef, is added to the beginning of the definition. 2. An identifier is required at the end of the block, the identifier is the type definition name 13
14
Structure Type Declaration
Variable Declaration Example: Declaration of structure type and variable. turbo C program examples 1 & 2, also show error simulation
15
Declaring and Initialization
Rules for structure initialization are similar to the rules for array intialization The initializers are enclosed in braces and separated by commas. They must match their corresponding types in the structure definition. When one or more intializers are missing, the structure elements will be assigned null values, zero for integers and floating-point numbers, and null(‘\0’) for characters and strings. Example: Initializing structures
16
Accessing Structure Referencing Individual Fields
Structure field can be accessed similar to an individual variable A field in a structure can be referred by referring to both the structure and the field. Syntex To refer to a field in a structure, use the structure variable- identifier and then the field identifier. The structure variable- identifier is separated from the field identifier by a dot. Example: Structure Direct Selection opeartor turbo C program example 3, also show error simulation
17
Nested Structures (1 of 4)
Structure in a structure is called a nested structure. Any number of structure can be nested, but normally not more than three. Example: Nested structure
18
Nested Structures (2 of 4)
Declaring Nested Structure Each structure is declared separately and then grouped in the high-level structure. Example: tyepdef struct { int month; int day; int year; }DATE; tyepdef struct int hoour; int min; int sec; }TIME; typedef struct { DATE date; TIME time; }STAMP; STAMP stamp; // variable declaration
19
Nested Structures (3 of 4)
Referencing Nested Structures To access nested structure, include each level from the highest to the component being referenced. Example: stamp stamp.date stamp.date.month stamp.date.day stamp.date.year stamp.time stamp.time.hour stamp.time.min stamp.time.sec turbo C program example 4, also show error simulation
20
Nested Structures (4 of 4)
Nested Structure Initialization Each structure must be initialized completely before proceeding to the next member. Each structure is enclosed in a set of braces. Example: STAMP stamp = {{105, 10, 1936}, (23, 45, 00}}; turbo C program example 5, also show error simulation
21
Structures containing arrays
Defining Arrays for Structure Structures can have one or more arrays as members Arrays can be accessed either through indexing or through pointers They are properly qualified with direct selection operator Example: Arrays in structures The student name and midterm stores are declared as arrays Initialization student s={“john”,{92,80,70},87}; Good morning Ladies and Gentlemen. Welcome to this talk on “Pointers in C,” presented by Michael. turbo c ex_5u6.c for error simulation
22
Array of structures (1 of 2)
An array of structures need to be created in many situations. Examples: Array of structure Use of an array of students to work with a group of students stored in a structure. Declare group of students as array Declare each student details as structure A structure declaration using arrays: struct student { char name[15]; int rollno; char gender; }; student stuAry[50]; Good morning Ladies and Gentlemen. Welcome to this talk on “Pointers in C,” presented by Michael. 22
23
Array of structures (2 of 2)
Initialization An array of structures can be initialized in the same way as arrays in C Example: Initializing an array of structures: struct student { char name[15]; int rollno; char gender; }; student stuAry[3]={ { “ram”,1234 , ‘m’} { “ravi”,2345 , ‘m’} { “sasi”,3456, ‘f’ } The above initialized values will be assigned by compiler as stuAry[0].name=ram stuary[0].rollno=1234 stuary[0].gender=m stuAry[1].name=ravi stuary[1].rollno=2345 stuary[1].gender=m stuAry[2].name=sasi stuary[2].rollno=3456 stuary[2].gender=f turbo c ex_5u1.c for error simulation 23
24
Structures and Functions (1 of 7)
Structures are fully useful if they can be passed to functions and return them. A function can access the members of a structure in three ways: Individual members can be passed to the function. The whole structure can be passed and the function can access the members using pass by value. The address of a structure can be passed, and the function can access the members through indirection and indirect selection operators.
25
Structures and Functions (2 of 7)
Passing individual members to a function In passing individual members to a function, use the direct selection operator to refer to the individual members for actual parameters. Actual parameters are structure variables Formal parameters simple variables like int ,char, float based on structure members
26
Structures and Functions (3 0f 7)
Example: Passing individual members to function turbo c ex_5u2.c for error simulation
27
Structures and Functions (4 0f 7)
Passing whole structure to a function using call by value Passing individual members is not a good programming technique A much better solution is to pass whole structure The actual parameters of function are structure variable names struct fraction fr1,fr2; Ex: multiply(fr1,fr2) The formal parameters are also structure variable names Ex: multiply(struct fraction fr1,struct fraction fr2) The function can also return a structure Ex:struct multiply(struct fraction fr1,struct fraction fr2)
28
Structures and Functions (5 0f 7)
Example: Passing and returning structures turbo c ex_5u3.c for error simulation
29
Structures and Functions (6 0f 7)
Passing individual members of structure to a function using call by reference Pointers are often used to pass structures It is also common to pass structures through pointers when structure is in dynamic memory In function call pass the address of a structure ex:multiply(&(fr1.numerator),&(fr1.denominator)) In function definition receive them in pointer variables ex: multiply(int *x,int *y) turbo c ex_5u4.c for error simulation
30
Structures and Functions (7 0f 7)
Passing structures through Pointer Pointers are often used 2 to pass structures It is also common to pass structures through pointers when structure is in dynamic memory In function call pass the address of a structure fraction fr1,fr2; ex:multiply(fraction &fr1,fraction &fr2) In function definition receive them in pointer variables ex: multiply(fraction *fr1,fraction *fr2) Example: Passing structure through Pointer
31
Structures and pointers ( 1 0f 3)
Structures containing pointers Structure can have pointers as members Pointers are very common in structures The use of pointers saves the memory Example: typedef struct emp { char *name int *empid; int salary; char *addr; }; turbo c ex_5u7.c for error simulation
32
Structures and pointers ( 2 0f 3)
Pointers to structures Structure like other data types can also be accessed through pointers. One of the most common methods used to reference structures. Example: Pointers to structures
33
Structures and pointers ( 3 of 3)
Indirect selection operator Operator-Indirect-Selection eliminates the problems with pointers to structured. Example: Indirect Selection Operator (*pointerName).fieldName « pointerName->fieldName. turbo c ex_5u8.c for error simulation
34
Self Referential Structures
A structure which references to itself is known as self referential structure Self referential structure mainly used in implementation of data structures Example : to create a node in single linked list struct node { int data; struct node* link; } In the above example node is pointing to node again until link assigned with null Example : to create a node in double linked list struct node *llink struct node* rlink; In the above example node is pointing to node again until link assigned with null turbo c ex_5u9.c for error simulation
35
Unions (1 of 3) The Union is a construct that allows memory to be shared by different types of data. A union is like a struct, but only one of its members is stored, not all I.e., a single variable may hold different types at different times Storage is enough to hold largest member Members are overlaid on top of each other Syntax: union union_name { <data-type> element 1; <data-type> element 2; <data-type> element 3; }union_variable; This code segment appeared in the appetizer. Unions
36
Unions (2 of 3) It is programmer’s responsibility to keep track of which type is stored in a union at any given time! Example struct taggedItem { enum {iType, fType, cType} tag; union { int ival; float fval; char *sval; } u; }; Unions are used much less frequently than structs — mostly in the inner details of operating system in device drivers in embedded systems where you have to access registers defined by the hardware Turbo c example.c with error simulation
37
Unions (3 of 3) Turbo c example2.c with error simulation Storage
Size of union is the size of its largest member Avoid unions with widely varying member sizes; for the larger data types, consider using pointers instead Referencing Unions Rules for referencing a Union are identical to those for structure Direct Selection (dot) operator is used to reference individual fields within the union When a union is referenced through pointer, the selection operator (arrow) can be used Example ShareData.num ShareData.chAry[0] Initialization Union may only be initialized to a value appropriate for the type of its first member The other types can only be initialized by assigning values or reading values into the union. Enclose the values in a set of broces, even if there is only one value, when initializing the union Turbo c example2.c with error simulation
38
Bit fields Bit field members must be ints
If space is a serious concern, you can select the number of bits used for each member struct CHAR { unsigned ch: 7; unsigned font: 6; unsigned size: 19; }; Layout possibilities (machine-dependent): Note: This won’t work on machines with 16-bit ints ch This code segment appeared in the appetizer. font size size font ch
39
Command-Line Arguments
Function main ( ) is used so far has been defined with no argument Function main( ) can also be defined with arguments Parameters used with main( ) are called Command line arguments Two arguments that can be passed to main function are argc and argv argc (argument count): it is of type Integer and defines the number of elements in an array for the second argument, argv argv (argument vector): it is a character array pointer that points to the user values stored in an array. Note: The users can define their own argument names but preferably argc and argv can be used.
40
Command-Line Arguments
Example: Defining Command-Line Arguments The following figure how argc and argv values stored in memory location \0 null 3 \0 \0 argc argv Format of argc and argv
41
Command-Line Arguments (1/3)
The execution of a command line argument program is different from a general program Program can be executed using Ms-dos shell(command prompt) Turbo c example16.c with error simulation
42
Command-Line Arguments (2/3)
Step for executing command line argument program :
43
FILES Objectives To understand the basic properties and characteristics of external files To understand the C implementation of file I/O using streams To write programs that read and write text files using the formatting function To write programs that read and write text files using the C character I/O function To write programs that handle simple I/O errors To understand and implement basic data validation concept
44
FILES (1/2) A file is an external collection of related data treated as a unit. The primary purpose of a file is to keep a record of data Files are required to store data in more permanent form since the contents of primary memory are lost when the computer is shut down. Files are stored in auxiliary secondary storage devices. Two most common forms of secondary storages are: (hard disk, CD and DVD) Tape
45
Files (2/2) Buffer: A temporary storage area that holds data as the computer transfers them to/from memory. The primary purpose of a buffer is to synchronize the physical devices (disk,tape) with a program’s requirement The buffer also holds data until it is efficient to write that data on to the storage device. Filename File name is used to read or write auxiliary storage file. Every operating system uses a set of rules for naming its file. Example abc.txt, xyz.doc etc. File information table A program to read or write file needs to know several pieces of information such as operating system name, the position of current character and so on. C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
46
STREAMS Text and Binary Streams
Data is input to and output from a stream. A stream can be associated with a physical device such as terminal, or with a file stored in auxiliary memory. Fig-1:Streams C uses two types of streams: Text stream A text stream consists of sequence of characters divided into lines with each line terminated by a newline character(\n) Binary stream A binary stream consists of sequence of data values such as integer real or complex using their memory representation.
47
Text Streams Stream file processing
A stream is an entity created by the program. To use a file in the program, the program’s stream name must be associated with the operating system’s file name. Four steps to processing a file 1. Create the stream 2. Open the which associates the stream name with the file name 3. Process file (read or write data) 4. Close the file
48
Text Streams Creating a Stream A stream is created when declared.
To declare a stream, use the FILE type FILE type is structure that contains information for reading and writing a file Syntax: FILE *ptr; Opening a file Once a stream has been created, it can be associated to a file. The standard open function can be used to open the file. The file open function returns address of the file type, which is stored in the stream pointer variable (*ptr). The file open function creates the stream, which can be referred to by its name.
49
Text Streams Using the Stream Name
The stream pointer is used in all functions that need to access the corresponding file for input (read) or output (write) Closing the stream : Close the file at the completion of file processing. Closing the file breaks the association between stream name and file name The stream is no longer available after the closing. Use the close function to release the file and destroy the contents of the file.
50
System-Created Streams
C provides standard streams in order to communicate with a terminal Streams must be created and associated with their terminal devices just like files. This is done automatically by ‘C’. Three stream pointers are declared and defined in the stdio.h header file. Stdin points to standard input stream. Stdout points to standard output stream. Stderr points to standard error stream.
51
Standard Library I/O Functions in C
The stdio.h header file contains different input/output function declarations Functions are grouped in eight different categories Three Functions viz file open/close, formatted input/output and character input/output will be covered as part of Text stream. 1 2 3 Fig-2:Standard I/O function
52
Standard Library I/O Function
File open (fopen) The file open function (fopen) serves two purposes: It makes the connection between the physical file and the file stream in the program. It creates a program file structure to store the information needed to process the file. Syntax: fopen(“filename”, “mode”); First parameter is filename and second parameter is mode A file name is string .the name consist of eight characters and three characters for file extension Ex: 1) text.txt 2) myfile.dat 3) stud.doc The file mode is a string that specifies the intend to use the file.
53
Standard Library I/O Function
Example spData = fopen(“MYFILE.DAT”, “w”); spData = fopen(“A:\\MYFILE.DAT”, “w”);
54
Standard Library I/O Function
File open modes The mode shows how to use the file: for reading, for writing or for appending. C has three different file modes as shown in table:
55
Standard Library I/O Function
File open modes Example File opening modes
56
Standard Library I/O Function
Read mode (r) Opens an existing file for reading . When a file opened in this mode, the file marker is positioned at beginning of file (the first character) The file must already exist. Otherwise, if does not, Null is returned as an error Opens a file for writing If the file does not exist, it is created If it already exists, it is opened and all its data are deleted It is an error to try to read from a file opened in write mode Write mode (w) Append mode (a) Opens an existing file for writing . New data is added or appended at the end of the file If the file does not exist, it is created and opened (the writing will start at the beginning of the file ) It is an error to read a file opened for append mode.
57
Standard Library I/O Function
File Close (fclose) File should be closed when no longer required to free system resources, such as buffer space. Use fclose function to close a file and the pointer variable Syntax: fclose(spData); Check the exp1 for file opening and closing
58
Formatted I/O Functions
There are two types of formatted I/O function: 1) Terminal I/O functions General I/O function Terminal I/O functions Read data from the key board and write data on to the monitor Example scont function: reads data from keyboard printf function: writes data on to monitor Syntax
59
Formatted I/O Functions
General I/O function Used to read from keyboard or any file and write on to monitor or any file. Example fscanf: reads from keyboard or any file fprintf: writes data on to monitor or any file Syntax
60
Formatted I/O Functions
Stream Pointer A pointer to the stream that has ben declared and associated with a text file. Example: User defined stream pointer FILE *fp; // declared as type file // fp=fopen(“text.txt”,”r”); fscanf(fp,”%s”,name); Example: Predefined stream pointer used with header file stdio.h fscanf(stdin,”%s”,name); fprintf
61
Formatted I/O Functions
Format control string Input and output functions use a format string Format string describes how data is to be formatted when read or written Format control string consists of three types of data 1) Whitespace 2) Text 3) Conversion specification Whitespace A whitespace character in an input format string causes leading write space characters in the input to be discarded A whitespace character in an output format string is copied to the output stream Text Any text character other than whitespace in input format string must match exactly the next character of the input stream. If it does not match, it causes conflict resulting in termination of operation Any text character in an output format string is copied to the output stream
62
Formatted I/O Functions
Conversion Specification conversion specification consists of a percentage character (%), optional formatting instructions and a conversion code The number, order and type of conversion specification must match the number, order and type of the parameters in the list. Otherwise it causes unpredictable results resulting in termination of input/output function Conversion specifications can have up to six elements as shown below: Example-2 for fprintf and fscanf The first element is a conversion specification token (%) and the last element is the conversion code. Both of these elements are required, the other elements are optional
63
Input Formatted Functions
scanf and fscnaf scanf and fscanf functions read text data and convert the data to the types specified by a format string scanf (scan formatted) reads data from standard input device(keyboard) fscanf (file scan formatted)reads the data from a file specified in the first parameter. This file can be standard input Syntax: scanf(“format string”, address list); fscanf(sp, “format string”, address list); sp represents stream pointer sp is the address of a stream defined as type File* A variable address must be included in the address list, otherwise causes “unpredictable and undefined” result
64
Input Formatted Functions
Input data formatting The conversion operation processes input character until any of the following occurs: 1) End of file is reached 2) An inappropriate character is encountered The number of characters read is equal to an explicitly specified maximum field width Ex: scanf(“%c %d”,&x,&y); fscanf(fp,”%c %d”,&x,&y);
65
Input Formatted Functions
Input conversion specification (scanf family) Size and conversion code for scanf
66
Input Formatted Functions
Input conversion specification Assignment Suppression Flag(*): specifies that the next input field is to be read by scanf, but not be stored and be discarded Example Int x; Float y; scanf(“%d %*c%f”,&x,&y); Width Specifies the maximum width of input (in characters). Allows to break out a code that may be stored in input without spaces. Ex: scanf(“%3d%2d%4d”,&n1,&n2,&n3); Example-3 for flag and width in input
67
Input Formatted Functions
Size A modifier for the conversion code. Ex: long int x; Conversion codes Integer (d): The decimal (d) format code reads only decimal digits and an optional plus or minus sign as the first character Octal and hexadecimal(o,x): ‘o’ is used to read octal value and ‘x’ is used for hexadecimal value Scientific notation (e,g,a): Used for scientific (real) argument type Count(n): verifies the number of input characters Ex:scanf(“%d %f %c %hn”,&x,&y,&z,&count); Example-4 for size and conversion code
68
Output Formatted Functions
printf and fprint Convert the data to the types specified by a format string in to text format for outputting printf (print formatted) writes data to a standard output device(monitor) fprintf (file print formatted) writes the data to a file specified in the first parameter Syntax: printf(“format string”, value list); fscanf(sp, “format string”, value list); sp represents stream pointer Value list is optional Ex: printf(“%d %c”x,y);//write to monitor fprinf(sp,”%d %c”,x,y);//write to file print conversion specifications
69
Output Formatted Functions
The table shows the flags, sizes and conversion code for printf family.
70
Output Formatted Functions
71
Output Formatted Functions
Flags Four output flags: Justification Padding Sign Alternate form The table defines the flag type, flag code and formatting Example-4 for flag implementation
72
Output Formatted Functions
Alternate Flag (#) Used with the real, engineering, hexadecimal and octal conversion codes. Width: Specifies minimum output width. However, it the data are wider than the specified width, C prints all the data only for output fields. Precision: It is specified as period followed by an ineger. Precision controls the following: a) To print minimum number of digits for integer b) The number of digits after the decimal point in float c) The number of significant digits in g and G output Size: The size specification is a modifier for conversion code and is used in combination with the conversion code. Ex:long int x=423444; Printf(“%ld”,x);//here ‘l’ is size specification for ineger Example-5 for width , precision and size
73
Output Formatted Functions
Conversion codes: Used to print numeric values in the specified formats. Inerger: (d and c): Signed decimal number. Format (c ) and (d) are identical for output. Unsigned (u): Unsigned decimal number. Octal and hexadecimal (o,x,X): Octal (o) and Hexadecimal (x for lowercase, X for upper case) Real (f): Decimal number with fraction. Exponent (e, E,g,G,a,A) Codes e and E format the number using (f), precision may be used to control number of digits after the decimal point Codes g and G: Scientific notation is used only when the exponent is less than – 4 or greater than specified precision. Codes a and A: Generates signed hexadecimal fractional representation with a decimal power-of-two exponent Count (n): Verifies the number of output characters Ex: printf(“%d %f %hn”,I,j,&count);//count variable is used to store number of character in printf statement.
74
Text versus binary streams
Binary Input/output Text versus binary streams Objectives To understand the difference between text and binary files. To write programs that read, write, and/or append binary files. To be able to process files reandomly.
75
Text versus binary streams
Binary Input/output Text versus binary streams Text and Binary File A file records data only in a binary format. However, a text file and a binary file are distinguish from each other. Text Files A file in which data are stored using only characters and is written using a text stream. Text files are read and written using input/output functions that convert the characters to data type as show below:
76
Binary Input/output Binary Files
A Binary file is a collection of data stored in the internal format of the computer. Binary files are read and written using binary streams known as block input/output functions. The data are stored in the file in the same format that they are stored in memory
77
Binary Input/output Differences between text and binary files
Major characteristics of Text files are: 1. All data in text file are human-readable graphic characters. 2. Each line of data ends with a new line character. 3. There is a special character called end-of-file(EOF) marker at the end of the file. Characteristics of Binary files are 1. Data are stored in the same format as they are stored in memory. 2. There are no lines or new line characters. There is an end-of-file marker. Figure shows how two data items are stored in a text file and in a binary file
78
Binary Input/output State of a File
An opened file is either in a read state, a write state or an error state. File must be in read or write state for reading or writing respectively. An error state occurs when trying to read a file in the write state and via-versa.
79
Binary Input/output State a File and Potential error condition
The Potential error conditions are shown below. Example As shown in the read mode (r ), only two states are possible, read and error. Trying to write in to the file in the read state, the state changes to error state.
80
Example-6 for fread and fwrite functions
Binary Input/output Opening Binary files The basic open operation is unchanged for binary file-only the mode changes. Syntax: FILE * fopen (const char* file name,const char*mode); File opening modes are shown below. The marker ( ) represents the end-of file marker. Closing Binary files Binary Files like text files, must be closed when no longer required. Closing destroys the file table and erases the logical file name. Syntax int fclose (FILE* sp); Example-6 for fread and fwrite functions
81
Standard Library Functions for Files
C has eight categories of standard file library functions. They are given below Four categories of functions which are more related to Binary Files are Block Input/output functions 2) Files Positioning 3) System File operation ) File status
82
Standard Library Functions for Files
Block Input/output Functions The block input and output functions are used to read and write data to binary files. The block read function is file read(fread). The block write function is file write(fwrite).
83
Standard Library Functions for Files
File Read (fread) fread reads a specified number of bytes from a binary file and places them into memory at the specified location. Declaration of fread () int fread ( void* pInArea, int element Size, int count, FILE* sp); pInArea is a pointer to the input area in memory. A generic void pointer is used to allow any pointer type to be passed to the function. elementSize and count are multiplied to determine how much data are to be transferred. The size is normally specified using the sizeof operator and the count is normally one when reading structures. Operator and the count is normally one when reading structures. The last parameter is the associated stream.
84
Standard Library Functions for Files
When fread is called, it transfers the next three integers from the file to the array, inArea. fread does not return end of file, it returns the number of elements read Example: file read that reads data into an array of integers.
85
Standard Library Functions for Files
File read (fread) Most common use of fread is reading structures(records). One advantage of block input/output functions is that one structure at a time can be transferred. Second advantage is that the data need not be formatted. Example: operation of fread when a structure is being read.
86
Standard Library Functions for Files
File Write (fwrite Writes a specified number of items to a binary file. Declaration : int fwrite(void* pOutArea, int elementsize, int count, FILE* sp); File Write Operation
87
Standard Library Functions for Files
File write (fwrite) Fwrite returns the number of items written. For example ,if it writes three integers, it returns 3. The return value, therefore, can be use to test the write operation. If the number of items written is fewer than count, then an error has occurred. The program should be aborted when we a write error is encountered. Writing a Structure Example-7 for fread and fwrite functions
88
File Status Functions Three functions to handle file status
1) test end of file (feof) 2) test error(ferror) 3) clear error(clearerr). Test End of File (feof) It is used to check if the end of file has been reached. The function returns non zero (true), if the file is at the end, otherwise returns zero (false) Declaration int feof(FILE* stream); Example: int feof(FILE* sp); //sp is file stream Test Error (ferror) Used to check the error status of the file. Trying to read a file in the write state or vice-versa results in error. ferror function returns true (non zero) if an error has occurred and returns false (zero) if no error occured Declaration: int ferror(FILE* stream);
89
File Status Functions Clear Error (clearerr)
when an error occurs, the subsequent calls to ferror returns non-zero, until the error status of file is reset The function clearerr is used to reset error status of the file. Declaration : void clearerr(FILE* stream); Example-8 for File status functions
90
File Positioning Functions
There are three file positioning functions: Rewind the file (rewind) Current location (ftell) Set position (fseek) 1) Rewind File (rewind) Sets the file position indicator to the beginning of the file. Declaration: void rewind(FILE* stream);
91
File Positioning Functions
Current Location (ftell) Reports the current position of the file relative to the beginning of the file. If the file position indicator is at the beginning of the file, ftell returns zero. Declaration long int ftell(FILE* stream); ftell returns the number of bytes from the beginning of the file. If these is a need to know the structure number relative to the first structure, then it must be calculated by dividing the ftell return value by the size of the structure. numchar =ftell(sp); numstruct=numchar/sizeof(STRUCTURE_TYPE); Ftell returns – 1, if an error, is encountered.
92
File Positioning Functions
3) Set Position (fseek): It positions the file location indicator to a specified byte position in a file. Decalon int fseek(FILE* stream, long offset, int wherefrom); Stream is a pointer to the open file. offset is a signed integer that specifies the number of bytes the position indicator must move absolutely or relatively.
93
File Positioning Functions
C provides three named constants that can be used to specify the starting point(wherefrom) of the seek. #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2 If wherefrom is SEEK_SET or 0 then the offset is measured absolutely from the beginning of the file. To position the file marker to the next record in a structure file, execute the following statement: Fseek(sp,sizeof(STRUCTURE_TYPE),SEEK_CUR); If where from is SEEK_CUR or 1 then the displacement is calculated relatively from the current file position Syntax fseek(sp, sizeof(STRUCTURE_TYPR), SEEK_CUR); If wherefrom is SEEK_END or 2, the file location indicator is positioned relative to the end of file. fseek(stuFile, OL, SEEK_END);
94
File Positioning Functions
File Seek operations
95
System File Operations
A few functions operate on the whole file instead of the contents. These functions use operating system calls to perform operations such as remove a file, rename a file, or create a temporary binary file. Remove File (remove) Removes or deletes the file using its external name. The parameter is a pointer to the name of the file. Syntax int remove(char* filename); Successful detection of the file, the function returns zero. Function returns non-zero, if the file can not be found. Rename File (rename) Used to rename the file. int rename(const char* oldfilename,const char* newfilename); It returns zero if renaming is successful and returns non-zero if there is an error.
96
System File Operations
Create Temporary File (tmpfile) Creates a new temporary output file. The file is available only while the program is running. It will be closed and erased when the execution of the program is finished. Declaration FILE* tmpfile(void); To create a temporary file, we first define a file pointer and then open it, as shown below. FILE* sp; Sp=tmpfile();
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.