0% found this document useful (0 votes)
36 views58 pages

PC Unit 5

This document discusses structures, unions, file management, and the C preprocessor in programming. It covers defining and declaring structures, arrays of structures, nested structures, passing structures to functions, unions, and enumeration. It also discusses file handling operations like opening, reading, writing and closing files, error handling, random access to files, and command line arguments. The preprocessor directives covered include file inclusion, macro substitution, and conditional compilation.

Uploaded by

Abhiram Pabolu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views58 pages

PC Unit 5

This document discusses structures, unions, file management, and the C preprocessor in programming. It covers defining and declaring structures, arrays of structures, nested structures, passing structures to functions, unions, and enumeration. It also discusses file handling operations like opening, reading, writing and closing files, error handling, random access to files, and command line arguments. The preprocessor directives covered include file inclusion, macro substitution, and conditional compilation.

Uploaded by

Abhiram Pabolu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

UNIT 5 - STRUCTURES AND UNIONS, FILE MANAGEMENT

 USER DEFINED DATA TYPES: INTRODUCTION

 STRUCTURE - DEFINITION & DECLARATION

 ARRAYS OF STRUCTURES & NESTED STRUCTURES

 PASSING STRUCTURES TO FUNCTIONS

 UNION & ENUMERATION AND TYPEDEF

 INTRODUCTION TO FILE HANDLING IN C

 INPUT AND OUTPUT OPERATIONS ON A FILE

 ERROR HANDLING

 RANDOM ACCESS TO FILES

 COMMAND LINE ARGUMENTS

 INTRODUCTION TO PRE-PROCESSOR

 MACRO SUBSTITUTION DIRECTIVES

 FILE INCLUSION DIRECTIVES

 CONDITIONAL COMPILATION DIRECTIVES

 MISCELLANEOUS DIRECTIVES
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

PART – A (2 Marks)

Two mark questions with answer

1. Briefly discuss about the purpose of pre-processor.


It helps for the generation of faster and
compactcode It saves the programmer„s time
It reduces the chances of inconsistency
It makes the modification of program easier.

2. List any four basic operations of file.


1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data into a file
5. Closing a file

3. Distinguish between feof and ferror.

feof: The feof() function is used to check whether the file pointer is at the end-of-file
or not. It takes the file pointer as the argument and returns non-zero if the file pointer
is at the end-of- file. Otherwise it returns zero.

Syntax: feof(fp);
Example: if(feof(fp1))
printf(“\nend of file”);

ferror: The ferror() function reports the status of the file indicated. It also takes a
FILE pointer as its only argument and returns a non zero integer if an error has been
detected up to that point, during processing. It returns zero otherwise.

Syntax: ferror(fp);
Example: if(ferror(fp1) !=
0) printf(“\nerror has
occured”);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

4. Discuss the different ways of opening a file.

File Type Modes of File


Operations
“r” open the file for read only.
“w” open the file for writing only.
“a” open the file for appending data to it.
r+ Read and write
w+ Write and read
“a+” Opens existing file for reading and writing.
“rb” open the binary file for read only.
“wb” open the binary file for writing only.
“r+b” or Opens a binary file for read and write operations.
“rb+”
“w+b” or Creates and opens binary file for read and write operations.
“wb+”
“a+b” or Opens a binary file for for read and write operations.
“ab+”

5. How can access files be randomly accessed?

Random access file only access the file at the point at which the data should be read or
written , rather than having to process it sequentially.

The Functions

fseek()-Repositions the file pointer to a stream. syntax:


fseek(fp,offset,position); ftell()-returns the current file pointer. syntax:
n=ftell(fp);
rewind() –takes the control back to the beginning of the file. syntax: rewind(fp);

6. What are the uses of getc and putc functions?


getc : It is used to read one character at a time from a file
syntax: c= getc(fp);
example: m=getc(fp1);

putc: used to write one character into a


file syntax: putc(c,fp)
example: putc(m,fp1);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

7. How to give the inputs to command line arguments?


The values of the arguments are supplied at the command prompt. the information
contained in the command line is passed to the program through the arguments argc
and argv. main(int argc , char *argv[] )
{
// body of the function
}
Argc :-Argc is an argument counter . It represents the number of
arguments in the command line .
Argv:-Argv is an argument vector . It representsan array of characters
pointersthat points to the command linearguments . The size of this array is
equalisequalto the value of argc.

8. What is a command line argument?


An executable program that performs a specific task for operating system is called as
operating system. The commands are issued from the prompt of operating system.
Some arguments are associated with the commands; hence these arguments are
called as command line arguments.

9. Define Pre-processor.
This is microprocessor program that processes the source program before it is
compiled. It is a collection of special statements called pre-processor statements or
pre-processor directives.
These directives are executed before the c program passes through the compiler.

10. Write the uses of #define.

 A macro is an operation defined by a #define pre-processor directive


 It creates symbolic constants and macros
 The macro identifier is replaced in the program with the replacement text before
the program is compiled.

11. Give the conditional pre-processing directives.

Directives permit certain segment of source code to be selectively compiled.


Directives are also called as Conditional Compilation.

The Conditional directives are


1. #if
2. #else
3. #elif
4. #endif
5. #ifdef
6. #ifndef

12. Write any eight built-in functions for file manipulation.


All C inbuilt functions which are declared in stdio.h header file are given
below. The source code for stdio.h header file is also given below for your
reference.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Function Operation
Name s
fopen() Creates a new file for use. Opens an existing file for
use.
fclose() Closes a file which has been opened for use.
fgetc() Reads a character from a file.
fputc() Writes a character to the file.
fprintf() Writes set of data values to a file.
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fseek() Sets the position to desired position in the file.
ftell() Gives the current position in the file.
rewind() Sets the position to the beginning of the file
fgets() Reads a string from the file
fputs() Writes a string to the file.
fread() Reads unformatted data from the file
fwrite() Writes unformatted data to the file

13. What role does the fseek() plays?


The fseek() function allows us to read from or write to any point in the stream
of bytes opened by using the fopen() function. It is used to move the position of the
file pointer to the desired location in the file.

Syntax fseek(fptr, offset, position)


Description fptr – file pointer of the file to be accessed.
offset – is a negative or positive number or a variable of long
integer data type to reposition the file pointer towards the
backward or forward direction from the location specified by
position.
position – Current position of the file pointer.

Example:

Beginning

fseek(fptr,5L,0);

5 byte
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

14. What are stream oriented data files?


Stream oriented data files are two types.
 In the first category, the data file comprises consecutive characters. These
characters can be interpreted as individual data items or as components of
strings or numbers. These are called text files.

 In the second category, often called as unformatted data files, organizes


data into blocks containing contiguous bytes of information. These blocks
represent more complex data structures, such as arrays and
structures. These files are called binary files

15. Define file inclusion.

It is the first type. This directive is used for including one or more files in the
program. It instructs the compiler to make a copy of specified file to be included
in place of the directive.

Syntax #include<filename>
#include“filename”
Description filename–name of the file that can be included in our
source program
“filename”-searches file in current directories and then in
standard directives.
< > - search only in standard directives
Example #include<stdio.h> contains standard I/O functions
in directories
#include”loop.c” written by the user.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

16. What is the purpose of #ifndef?

#ifndef checks whether the given token has been #defined earlier in the file or in an
included file; if not, it includes the code between it and the closing #else or, if no #else
is present, #endif statement. #ifndef is often used to make header files idempotent by
defining a token once the file has been included and checking that the token was not
set at the top of that file.
17. Give the syntax of fopen().

Syntax: fptr = fopen(“filename”, ”mode”);

Assigned as
an identifier to
the FILE

FILE *fptr; fptr acts as a pointer to


the
data
Deacription: filename – Assigned as an identifier to the file
fptr – Acts as a pointer to the data
FILE - defined Data type.
Example: fptr = fopen(“computer”, ”r”);

18. Write the uses of #define.


1. A macro is an operation defined by a #define pre-processor directive
2. It creates symbolic constants and macros
3. The macro identifier is replaced in the program with the replacement text before
the program is compiled.

19. What is meant by Preprocessor in C?


The preprocessor is the part of the compiler in C and C++ that reads the
source code files and expands text wherever it finds a # in column one.

20. List the common Preprocessor directives.


• File inclusion.
o #include “file name”
o #include <filename>
• Macro substitution.
o #define identifier string/integer
• Conditional inclusion.
o #include
o #define
o #ifdef
o #else
o #undef
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

21. Write the rules for defining preprocessor.


• Every preprocessor must start with # symbol.
• The preprocessor is always placed before main() function.
• It cannot have termination with semicolon.
• There is no assignment operator in #define statement.
• The conditional macro must be terminated with #ifdef, #endif.

22. Give the use of preprocessor


Use of the preprocessor is advantageous since it makes:
 programs easier to develop,
 easier to read,
 easier to modify
 C code more transportable between different machine architectures

23. Define macro substitutions.


A macro substitution is used to define symbolic constants in the source program. The
identifier or string or integer defined is replaced by Macro substitution.
Syntax: #define identifier string/integer

24. Give syntax for Structure declaration.


struct structure_name
{
Structure_member 1;
Structure_member 2;
…….
Structure_member n;
}; v1,v2,…,vn;
25. Give simple example for preprocessor.
#define square(n) (n*n)
#define cube(n) (n*n*n)
#include<stdio.h>
main()
{
int a=5,b=3,s,c;
s=square(a);
c=cube(b);
printf(“Square value of 5 is
%d\n”,s); printf(“Cube value of 3 is
%d”,c);
}

26. Write notes on Dynamic memory allocation.


The process of allocating memory at run time is known as dynamic memory allocation.
Ie., It allows us to allocate additional memory space or to release unwanted space at the
time of program execution. This is known as Dynamic memory allocation.

27. Write notes on Dynamic memory allocation.


The process of allocating memory at run time is known as dynamic memory allocation.
Ie., It allows us to allocate additional memory space or to release unwanted space at the
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

time of program execution. This is known as Dynamic memory allocation.

28. Write the advantages of dynamic memory allocation.


• It has the ability to reserve or allocate additional memory space during the program
execution.
• It has the ability to release unwanted memory space during the program execution.
• It is very useful to modify the size of the previously allocated memory.
• It is very useful to allocate memory space to an array of elements and initialize them to zero.

29. What is the use of malloc()? Give its syntax.


It is used to allocate block of memory i.e., it allocates a block of memory of specified
size and return a pointer of type void.

Syntax: pointer_variable = (type cast*)malloc(size in bytes);

30. List out the dynamic memory allocation function.


Task
malloc
Allocates memory requests size of bytes and returns a pointer to the Ist byte of
allocated space.
calloc
Allocates space for an array of elements initializes them to zero and returns a
pointer to the memory.
free
Frees previously allocated space.
realloc
Modifies the size of previously allocated space.

31.What is meant by Command line arguments?


An executable program that performs a specific task for operating system is called a
Command. Some arguments are to be associated with the commands hence these
arguments are called as command line arguments.

Eg. int main(int argc, char *argr[])

32.Why do we need files?


 In order to efficiently analyze all the data that has been collected from different
sources.
 Storing data as files in permanent storage devices like hard disk so to make
availability of
data for future use.

33. Define the term file.


 A file is a collection of related data stored on a secondary storage device like hard disk.
 Every file contains data that is organized in hierarchy as fields, records, and databases.

34. What do you mean by streams?


 Stream is a Sequence of data bytes, which is used to read and write data to a file.
 A Stream acts as an interface between a program and an input/output Device.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

35. Write about Input and Output stream.


 Input streams get the data from different input devices such as keyboard and
mouse and provide input data to the program.
 Output Streams obtain data from the program and write that on different Output
Devices
such as Memory or print them on the Screen.
36.Why do we need buffer in files? (or) Why do we use buffer in files?
A buffer is a block of memory that is used for temporary storage of data that has to be read
from or written to a file.
The buffer acts as an interface between the stream (which is character-oriented) and the disk
hardware (which is block oriented).

37.List the different types of files


Text file or ASCII text file: It is a stream of characters that can be processed sequentially and in
forward direction only.
Binary file: It is collection of bytes.
Sequential File: Data is stored sequentially, to read the last record of the file, we need to
traverse all the previous records before it. Eg: files on magnetic tapes.
Random Access File: Data can be accessed and modified randomly. We can read any record
directly. Eg: files on disks.

38..What are the different files attributes.


Filename - String of characters to store the name of files.
File Position -Pointer that points the position at which next read and write operation to be
performed.
File Structure -It indicates whether file is text or binary file.
File Access Methods- Indicates whether file can be accessed sequence or randomly
Attributes flag: Specifies that hidden or read-only or archive file.

39.What is a file pointer?


A file pointer fp is a pointer to a structure of type FILE. It is used to access a particular file from
number of files from the disk. FILE *fp;
40.Differentiate between binary file and text file.

TEXT FILE BINARY FILE


Data are human readable characters. Data is in the form of sequence of bytes.

Each line ends with a newline character There are no lines or newline character

Ctrl+z or Ctrl+d are end of file character. An EOF marker is used

Data is read in forward direction only. Data may be read in any direction.
Data is converted into the internal format Data stored in file are in same format
before being stored in memory that they are stored in memory.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

41.What are the different Standard I/O file function in C?


Standard I / O File Functions:
fputc() fgetc() Individual characters
fputs() fgets() Character Strings
fputs() fscanf() Formatted ASCII
fwrite() fread() Binary files
write() read() Low-level binary

42.List the various file operations.


 Creating a new file
 Opening an existing file
 Reading from a file
 Writing to a file
 Moving to a specific location in a file (seek)
 Closing a file

43.What are the steps to be followed when using a file?


 To use files in C, we must follow the steps given below.
 Declare a file pointer variable
 Open the file
 Process the file
 Close the file

44.What are the different modes in which a file can be opened?


 r Open text file for reading.
 w Open text file for writing. previous content, if any then discarded
 a Open or create file for writing at the end of the file.
 r+ Open text file for update
 w+ Create or open text file for update, previous content lost, if any
 a+ Open or create text file for update, writing at the end.

45.What is the difference between getc( ) and getchar ()


getc():

It reads a single character from a given input stream and returns the
corresponding integer value (typically ASCII value of read character) on success. It
returns EOF on failure.

Syntax:
int getc(FILE *stream);

Example:
// Example for
getc() #include
<stdio.h>
int main()
{
printf("%c",
getc(stdin));
return(0);
}
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

getchar():

getchar() is a function call: it reads in a single character and waits for the user to
hit 'enter key' before reading the character.

Syntax:
int getchar(void);

Example:
// Example for
getchar() #include
<stdio.h>
int main()
{
printf("%c",
getchar()); return
0;
}

46. Write a simple program to read the numbers from the file and display numbers.
#include<stdio.h#
include<conio.h>
void main()
{
FILE *f1;
int
number,i;
clrscr();
printf("Contents of DATA file\n\n");
f1 = fopen("DATA","w"); /* create
a data file */ for(i=1;i<=30;i++)
{
scanf("%d",&num
ber); if(number==-
1)break;
putw(number,f1);
}
fclose(f1);
f1 = fopen("DATA","r");
while((number = getw(f1)) != EOF) /* Read from Data file */
{
if(number%2=
=0)
putw(number,f
1); fclose(f1);
getch();
}
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

47.Define Structure in C.
C supports a constructed data type known as structures, a mechanism for
packing data of different types. A structure is a convenient tool for handling a group
of logically related data items. This is known as Structure.

48.Write the rules for declaring a structure.


• A structure must end with a semicolon.
• Usually a structure appears at the top of a program.
• Each element of structure must be terminated.
• The structure variable must be accessed by using dot (.) operator

49.Write the rules for initializing structure.


• The individual data members of structure cannot be initialized.
• The structure variables can be initialized at compile time only.
• The order of data members in a structure must match the order of values in
enclosed brackets.
• We can initialize only some of the data members of the structure.
• The uninitialized data members can be initialized by default with zero for int and float
„\0‟for character and strings.

50.What is mean by nested structure?


It is otherwise known as structure within structure, i.e., a structure appear within
another structure. This is called nested structure.

51. Define Union in C.


Union is also derived data types like as structure. All the members of union use the
same location, although a union may contain many members of different types. The
keyword union is used to declare union.

52.Differentiate: Structure and Union.


Structur Union
e
1. It allocates memory equal to sum of 1. It allocates piece of memory that is
memory allocated to its each individual Large
member. enough to hold the Largest variable of
type in union.
2.each member have their own memory 2. one block is used by all the members
space. of
union.
3. structure cannot be implemented in 3. Union is the Best environment where
shred memory memory is shared.
4. Self referential structure can be 4. self ref. union cannot be implemented.
implemented in data structure.
5. All members if structure can be 5. only one member is accessed at a
accessed time.
at a time.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

53.Write the features of Structure.


The values of a structure variable can be assigned to another structure variable of
the same type using the assignment operator. It is not necessary to copy the
structure elements.
54.What are the advantages of union over structure? (0R) State
the importance of union.
• All the members use the same memory space to store the values.
• Keyword union is used.
• Only its first members may be initialized.
• Different interpretation for the same memory location is possible.
• Conversion of memory is possible.

55.How does a structure differ from an array?

Arrays Structures
1. An array is a collection of 1. Structure can have elements of
related data elements of different types
same type.
2. An array is a derived data 2. A structure is a
type programmer- defined data
type
3. Any array behaves like a 3. But in the case of structure,
built-in data types. All we have first we have to design and
to do is to declare an array declare a data structure before the
variable and use it. variable of that type are declared
and used.

56.Give syntax for Structure declaration.


struct structure_name
{
Structure_member 1;
Structure_member 2;

…….
Structure_member n;
}; v1,v2,…,vn;

57.Give the applicability of union in programming.


 Union is a derived data type
 Used to conserve memory.
 Same memory shared by two or more variables.
 Variables that share memory location differ in data types.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

58.Compare structure and union.

S.No Structure Union


s s
Each member in a Structure
occupies and uses its own All the members of a Union use
1 the same memory space.
memory space.
The key word Struct tells us that The key word Union tells us that
2 we are dealing with structure. we are dealing with Unions.
All the members of a Structure Only the first member of a Union
3 can can
be initialized. be initialized.
The members of a Structure are
The members of an Union are
4 not stored in sequence of
stored in sequence of memory
memory
locations. locations.
More memory space is Less memory space is required
5 required since each member since all members are stored in
is stored in a the same
separate memory locations. memory locations.

59.Give an example where a structure data type may be required.


A Structure is a collection of one or more variables possibly of different data types
grouped together under a single name for convenient handling.
struct books
{
char book_name[50];
int pages;
float price;
}b1;

60.What is a user – defined data type?


C supports the features “typedef” that allows users to define the identifier which would
represent an existing data type. This defined data type can then be used to declare variables:

Syntax:
typedef int numbers;
eg: numbers num1,num2;
In this example, num1 and num2 are declared as int variables.
The main advantage of user defined data type is that it increases the program‟s readability.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Enumerated type:
This is also a user defined data type. “Enum” is the keyword and “identifier” is the
user defined data type that is used to declare the variables. It can have any value
enclosed within the curly braces.

Syntax:
enum identifier {value1,value2, value 3,…}

For example:
enum day
{January,February,March,April,..}; enum
day month_st,month_end;

61.Define Union?
Unions are same as structures except that they differ in storage. Unions have
members of different data types. All the members of a union share the same storage
area within the memory. At any time only one value can be stored.
union exam
{
introll_no;
char name[15];
int mark1,mark2,mark3;
};

62.Write about nested structure?

Nesting of structures are nothing but structure within another structure (i.e., a
structure can contain one or more structures embers).
A structure may be defined and/or declared inside another structure.
struct employee
{
int empno; char
name[15];
struct dob
{
int date ,
int month, int
year;
} d;
}emp;

63.What is the use of structure in C.


1. It is a complex data type declaration that defines a physically grouped list of
variables to be placed under one name in a block of memory, allowing the different
variables to be accessed via a single pointer, or the struct declared name which
returns the same address.
2. For increasing the execution speed.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

64.Write the syntax for declaration and initialization of structures.


Syntax:
struct structure_name
{
data type data member1;

data type data member2;


.......
.......
data type data member n;
}structure variable={list of values};
Example:
struct student //declaration
{
int rno;
char name[20];
float cgpa;
}s={10,”amirtha”,95}; //initialization

65.What is a structure variable?


struct book_bank
{
char bname[50];
char author[50]; int
pages;
float price;
}book1;
The members of a structure themselves are not variables. They do not occupy any
memory until they are associated with the structure variables such as book1. When the
compiler comes across a declaration statement, it reserves memory space for the
structure variables. It is also allowed to combine both the structure definition and
variables declaration in one statement.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

PART – B (5 Marks & 10 Marks)


1.STRUCTURE
DEFINITION
It is a user defined data type. A structure is a collection of variables of different
types grouped together under a single name. By using structures we can make a
group of variables, arrays, pointers and etc..,

DECLARATION OF STRUCTURES
It contains data members and each is accessed by the structure variable. A
structure is declared using the keyword struct followed by a structure name. All
the variables of the structures are declared within the structure.

Syntax: struct structure_name


{
structure_element 1;
structure_element 2;

structure_element n;
};struct structure_name v1,v2,…,vn;

Example:
struct student
{
int marks;
float avg;
char grade;
};

The structure definition does not allocate any memory. Structure provides a model
of how the structure is to be in memory and gives details of the member names.
Memory is allocated for the structure when we declare a variable of the structure.

struct student
{
int marks;
float avg;
char grade;
}s; // Declaring Structure Variable
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Memory allocation for above structure is

2000 2001 2002 2003

int marks
av
float g

char grade

INITIALIZATION OF STRUCTURES
Initializing a structure means assigning some constants to the members of the
structure. The
initializes are enclosed in braces and are separated by commas.
Example:
struct student
{
int r_no;
char name[20]; char course[20]; float fees;
}struct student stud1 = {01, “Rahul”, “IT”, 45000};

Rules of Initializing Structures


1. We cannot initialize individual members inside the structure template
2. The order of values enclosed in braces must match the order of members in the
structure definition
3. It is permitted to have a partial initialization. We can initialize only the first few
members and leave the remaining blank. The uninitialized members should be only
at the end of the list.
4. The uninitialized members will be assigned default values as follows
• Zero for integer and floating point number.
• „/0‟ for characters and strings.

ACCESSING THE MEMBERS OF A STRUCTURE


Array elements are accessed using the Subscript variable, Similarly Structure
members are accessed using dot [.] operator. It is called as “Structure member
Operator”. Use this Operator in between “Structure name” & “member name”

Syntax:
struct_var.member_name;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Example:
stud1.rno = 01;
strcpy(stud1.name, “Kalam”);
stud1.course = “IT”;
stud1.fees = 45000;

Here the dot is an operator which selects a member from a structure.

Selecting a member from a structure pointer happens frequently, it has its own
operator -> which acts as follows. Assume that stud1 is a pointer to a structure of
type student we would refer to the name member as

stud1.rno->name

PROGRAM USING STRUCTURES TO READ AND DISPLAY THE INFORMATION


ABOUT A STUDENT

#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[80]; float fees;
char DOB[80];
};
int main()
{
struct student stud1;
clrscr( );
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud1.rollno);
printf(“\n Enter the name : “);
scanf(“%s”, stud1.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud1.fees);
printf(“\n Enter the DOB : “);
scanf(“%s”, stud1.DOB);
printf(“\n ********STUDENT‟S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.rollno);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n FEES = %f”, stud1.fees);
printf(“\n DOB = %s”, stud1.DOB);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

getch( );
}

OUTPUT:
Enter the roll number: 101
Enter the name: Rahul
Enter the fees: 45000
Enter the DOB: 11.2.1995
********STUDENTÆS DETAILS *******
ROLL No. = 101
NAME. = Rahul
FEES = 45000.000000
DOB = 11.2.1995

2.ARRAYS OF STRUCTURES
An array of structures is the same way as we declare an array of built-in data type.
The array of structures can be used when common structure definition is need for
the process of information.

Syntax

struct struct_name struct_var[index];

Example
struct student stud[30];

Now, to assign values to the ith student of the class, we will write,
stud[i].r_no = 09;
stud[i].name = “RAM”;
stud[i].course = “CSE”;
stud[i].fees = 60000;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

/*program to read and display information of all the students in the


class*/
#include<stdio.h>
#include<conio.h>
struct studentinfo
{
int roll;
char name[20];
int age;
};
void main()
{
struct studentinfo s[100];
clrscr();
int n,i;
printf("\nHow many students information do you want to enter?");
scanf("%d",&n);
printf("Enter Student Information:");
for(i=1;i<=n;i++)
{
printf("\nEnter Roll no.:");
scanf("%d",&s[i].roll);
printf("\nEnter the name of the student:");
scanf("%s",&s[i].name);
printf("\nEnter the age of the student:");
scanf("%d",&s[i].age);
}
printf("\n\nInformation of all studenst:");
for(i=1;i<=n;i++)
{
printf("\nRoll no.:%d",s[i].roll);
printf("\nName:%s",s[i].name);
printf("\nAge of student:%d\n\n",s[i].age);
}
getch( );
}
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

3.NESTED STRUCTURES
A structure can be placed within another structure. That is, a structure may contain
another structure as its member. Such a structure that contains another structure
as its member is called a nested structure.

Example:
/*Program to read and display the information of student using nested Structure*/
#include<stdio.h>
#include<conio.h>
struct DOB
{
int day;
int month;
int year;
};

struct student
{
int roll_no;
char name[100];
float fees;
struct DOB date;
};

int main( )
{
struct student stud;
clrscr( );
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

printf(“\n Enter the roll number : “);


scanf(“%d”, &stud.roll_no);
printf(“\n Enter the name : “);
scanf(“%s”, stud.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud.fees);
printf(“\n Enter the DOB : “);
scanf(“%d %d %d”, &stud.date.day,&stud.date.month,&stud.date.year);
printf(“\n ********STUDENT‟S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud.roll_no);
printf(“\n NAME. = %s”, stud.name);
printf(“\n FEES. = %f”, stud.fees);
printf(“\n DOB = %d - %d - %d”, stud.date.day, stud.date.month,stud.date.year);
getch( );
}

OUTPUT:

Enter the roll number: 101


Enter the name: rahul
Enter the fees: 45000
Enter the DOB: 11.2.1995

********STUDENTÆS DETAILS *******


ROLL No. = 101
NAME. = Rahul
FEES = 45000
DOB = 11.2.1995

Example:

#include<stdio.h>
struct employee
{
char name[20];
struct address
{
char city[20];
int pin;
char phone[14];
}add;
};
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,&emp.add.city, &emp.add.pin, &emp.add.pon
e);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,
emp.add.city, emp.add.pin,emp.add.phone);
}
OUTPUT
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890

4.STRUCTURE AND FUNCTIONS


Similar to arrays and pointers a structure can also be passed to a function. There
are three ways of passing a structure to a function.
They are;

1. Passing individual structure members as arguments to


functions.
2. Passing the address of structure as arguments to
functions.
3. Passing the entire structure as arguments to functions.

1. PASSING A STRUCTURE MEMBER TO FUNCTIONS

 This method is used to pass each member of the structure as an


actual argument of the function call statement.

 When you pass a member of a structure to a function as an


argument, you are actually passing the value of that member to the
function.

 The arguments are then treated independently as ordinary variables.

 For example;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

struct employee
{
int empno;
char
empname[20];
float salary;
} emp;

 The member of the structure can be passed to the function employ() as

 employ(emp.empno)
 employ(emp.empname)
 employ(emp.salary);

 Where employ(emp.empno) passes the integer value of empno to the


function employ().
 Employ(emp.empname[1]) passes the character value empname to the
function employ().
 Similarly employ(emp.salary) passes the float value of salary to the function
employ().
 This method is the most common method and becomes inefficient when
the structure is large.

Example
#include <stdio.h>
int add(int, int) ; //function declaration
int main()
{
//structures declartion
struct addition{
int a, b;
int c;
}sum;
printf("Enter the value of a : ");
scanf("%d",&sum.a);
printf("\nEnter the value of b : ");
scanf("%d",&sum.b);
sum.c = add(sum. a, sum.b); //passing structure members as arguments to
function
printf("\nThe sum of two value are : ");
printf("%d ", sum.c);
return 0;
}
//Function definition
int add(int x, int y)
{
int sum1;
sum1 = x + y;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

return(sum1);
}
Output
Enter the value of a 10
Enter the value of b 20
The sum of two values 30

2. PASSING THE ADDRESS OF STRUCTURE AS ARGUMENT TO FUNCTIONS

 The member of a structure can also be passed to function by passing


the address of the structures.

 In this, a method the address location of the structure is passed to


the called function, hence the address operator (&) is used before the
structure name.

Example
#include<stdio.h>
struct date{
int day;
char month[10];
int year;
};
int main(){
struct date d;
printf("enter the day,month and year:");
scanf("%d%s%d",&d.day,d.month,&d.year);
display(&d);
return 0;
}
void display(struct date *p){
printf("day=%d\n",p->day);
printf("month=%s\n",p->month);
printf("year=%d\n",p->year);
}
OUTPUT
enter the day, month and year:20 MAR 2021
day=20
month=MAR
year=2021

3. PASSING ENTIRE STRUCTURE TO FUNCTIONS

In this method, the entire structure is passed as an argument to the function, since
the function is working on a copy of the structures, any changes made to the
structure members within the function are not reflected in the original structure.
Therefore, it is necessary for the function to return the entire structure back to the
calling function.

Example:
#include<stdio.h>
void employ(struct employee emp);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

struct employee
{
int empno;
char empname[20];
};
main()
{
struct employee emp1;
printf(“\nEnter Employee No. and Name : “);
scanf(“%d%s”,&emp1.empno,emp1.empname);
employ(emp1);
}

void employ(struct employee emp)


{
printf(“\nThe Employee No. is : %d”, emp.empno);
printf(“\nThe Employee Name is : %s”, emp.empname);
}

OUTPUT:

Enter Employee No. and Name: 101 David


The Employee No. is: 101
The Employee Name is: David

Example:
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
void display(struct student);
int main()
{
int i;
struct student st;
printf("Enter Records of students");
printf("\nEnter Rollno:");
scanf("%d",&st.rollno);
printf("\nEnter Name:");
scanf("%s",&st.name);
display(st);
getch();
return 0;
}
Void display(struct student st)
{
printf("\nStudent Information List:");
printf("\nRollno:%d, Name:%s",st.rollno,st.name);
}
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

OUTPUT
Enter Records of students
Enter Rollno:
11
Enter Name:
Sonoo
Student Information List:
Rollno:11,
Name: Sonoo

5.USER –DEFINED DATA TYPES


TYPEDEF

C provides a capability that enables the programmer to assign an alternate


name to a data-type. This is done with a statement known as typedef
 typedef declaration do not introduce new type but introduces new name or
creating synonym (or alias) for existing type.
 To construct shorter or more meaningful names for types already defined by
the language or for types that you have declared.
 A typedef declaration does not reserve storage.
 The name space for a typedef name is the same as other ordinary identifiers.
 Therefore, a program can have a typedef name and a local-scope identifier
by the same name.
 The exception to this rule is if the typedef name specifies a variably modified
type. In this case, it has block scope.
 The syntax is,
typedef type-declaration the_synonym;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Using typedef with structures


we can use typedef with structure to define a new data type and then use
that data type to define structure variables directly as follows

struct student
{
char name[20];
int age;
};
struct student s1;

we use the typedef keyword to create the variable of type student.

struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;

Now we can use the stud variable in a program to create the variables of
type struct student.
The above typedef can be written as:

typedef struct student


{
char name[20];
int age;
} stud;
stud s1,s2;

Example
#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",s1.name);
printf("\nEnter the age of student:");
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}

Output
Enter the details of student s1:
Enter the name of the student:
Peter
Enter the age of student:
28
Name of the student is : Peter
Age of the student is : 28

Example
#include <stdio.h>
//structures declaration
typedef struct addition{
int a, b;
}sum;
void add(sum) ; //function declaration with struct type sum
int main()
{
sum s1;
printf("Enter the value of a : ");
scanf("%d",&s1.a);
printf("\nEnter the value of b : ");
scanf("%d",&s1.b);
add(s1); //passing entire structure as an argument to function
return 0;
}
//Function Definition
void add(sum s)
{
int sum1;
sum1 = s.a + s.b;
printf("\nThe sum of two values are :%d ", sum1);
}
Output
• Enter the value of a 10
• Enter the value of b 20
• The sum of two values 30

ENUM
 enum is another user-defined type consisting of a set of named constants
called enumerators.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

 Using a keyword enum, it is a set of integer constants represented by


identifiers.

 The syntax is shown below,


enum enum_name{const1, const2, ....... };

 These enumeration constants are, in effect, symbolic constants whose values


can be set automatically.
 The values in an enum start with 0, unless specified otherwise, and are
incremented by 1. For example, the following enumeration,
enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};
 Creates a new data type, enum days, in which the identifiers are set
automatically to the integers 0 to 6.
 To number the days 1 to 7, use the following enumeration,
enum days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};
 Or we can re-arrange the order,
enum days {Mon, Tue, Wed, Thu = 7, Fri, Sat, Sun};

Example
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Sat
urday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}

Output
The value of w is 2
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Example
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};

int main()
{
enum days d;
d=monday;
switch(d)
{
case sunday:
printf("Today is sunday");
break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}

return 0;
}
OUTPUT
Today is Monday

6.UNION
A union is a special data type available in C to store different data types in the
same memory location. We can define a union with many members, but only one
member can contain a value at a time. Unions provide an efficient way of using the
same memory location for multi-purpose.

DEFINITION
Defining a union, is very similar as like defining structure but keyword union is
used. The union statement defines a new data type, with more than one member
for your program.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Syntax:

union
{
member definition;
member definition;

...
member definition;
} [one or more union variables];

Each member definition is a normal variable definition, such as int i; or


float f; or any other valid variable definition. At the end of the union's
definition, before the final semicolon, union variables are declared.
Example:

union sample
{
int marks;
float avg;
char grade;
};

Now, a variable of sample type can store an integer, a floating-point number, or a


string of characters. This means that a single variable ie. same memory location
can be used to store multiple types of data. We can use any built-in or user defined
data types inside a union based on requirement.

Memory allocation
 In structure
struct student
{
int rollno;
char gender;
float marks;
};
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

 In union

union student
{
int rollno;
char gender;
float marks;
};

INITIALIZING THE UNION


We can initialize the union in various ways. For example

ACCESSING UNION MEMBERS


To access any member of a union, the member access operator (.) is used. would
The union keyword to define variables of union type. Following is the example to
explain usage of union:
#include <stdio.h>
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

#include <conio.h>
union number
{
int n1; float n2;
}union number x;

void main()
{
clrscr() ;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
}
Output:
Enter the value of n1:10
Value of n1 =10
Enter the value of n2:20.5
Value of n2 =20.50000

7.INTRODUCTION TO FILE HANDLING


Definition of Files

“A file is a collection of related information that is permanently stored on


the disk and allows us to access and alter the information whenever
necessary.”
Need of Files:
 In order to efficiently analyze all the data that has been collected from different
sources.
 Storing data as files in permanent storage devices like hard disk so to make
availability of data for future use.

Definition:
 A file is a collection of related data stored on a secondary storage device like
hard disk.
 Every file contains data that is organized in hierarchy as fields, records, and
databases
 Stored as sequence of bytes, logically contiguous (may not be physically
contiguous on disk).
 Streams
 Stream is a Sequence of data bytes, which is used to read and write data to
a file.
 A Stream acts as an interface between a program and an input/output
Device.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Input and Output stream:


 Input streams get the data from different input devices such as keyboard
and mouse and provide input data to the program.
 Output Streams obtain data from the program and write that on different
Output Devices such as Memory or print them on the Screen.
 Buffer in files:
 A buffer is a block of memory that is used for temporary storage of data that
has to be read from or written to a file.
 The buffer acts as an interface between the stream (which is character-
oriented) and the disk hardware (which is block oriented).

 Field: Single unit in the file


 Record :It is logical group of data fields that comprise a single row of
information, which describes the characteristics of an item.
 Directory: It is a collection of related files.

 Standard streams available in C language


 standard input (stdin) - Standard input stream from which program
receives its data
 standard output (stdout) -Standard output stream where a program
writes its output data
 standard error (stderr)- Standard error an output stream used by
programs to report error messages.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

 Types of files
 Text file or ASCII text file: It is a stream of characters that can be
processed sequentially and in forward direction only.
 Binary file: It is collection of bytes.
 Sequential File: Data is stored sequentially, to read the last record of
the file, we need to traverse all the previous records before it. Eg: files on
magnetic tapes.
 Random Access File: Data can be accessed and modified randomly. We
can read any record directly. Eg: files on disks.

 File attributes.
The various file attributes are:
 Filename - String of characters to store the name of files.
 File Position -Pointer that points the position at which next read and write
operation to be performed.
 File Structure -It indicates whether file is text or binary file
 File Access Methods- Indicates whether file can be accessed sequentially or
randomly
 Attributes flag: Specifies that hidden or read-only or archive file.

File operations.
• Creating a new file
• Opening an existing file
• Reading from a file
• Writing to a file
• Moving to a specific location in a file (seek)
• Closing a file

8.DEFINING AND OPENING A FILE

FILE *fptr;

General form of declaring a file.

FILE is a defined Data type. FILE should be compulsorily written in Uppercase.


The pointer fptr is referred to as the stream pointer. This pointer contains all
the information about the file. Before performing any Input/Output operation
in a file, it must be opened by the program. Opening a file established a
connection between the file and the program in which the file is opened. Once
the file has been opened, the program can perform Input/Output process on
the file.

While opening the file, the following should be specified.


 Name of the file.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

 Purpose of opening the file (i.e., for reading or writing or appending etc.,)

fopen() function is used to open a file. It accepts two arguments, first


argument is the name of the file, and the second argument is the mode in
which the file is to be opened.
Syntax:
FILE *fptr;
fptr = fopen(“filename”, ”mode”);

Description: filename – Assigned as an identifier to the file


fptr – Acts as a pointer to the data
FILE - defined Data type.

Example: fptr = fopen(“computer”, ”r”); //*r- opens the file in read


mode*//

File Modes of File


Type Operations
“r” open the file for read only.

“w” open the file for writing only.

“a” open the file for appending data to it.

r+ Read and write

w+ Write and read

“a+” Opens existing file for reading and writing.

“rb” open the binary file for read only.

“wb” open the binary file for writing only.

“r+b” Opens a binary file for read and write operations.

or “rb+”
“w+b” Creates and opens binary file for read and write
operations.
or
“wb+”
“a+b” Opens a binary file for for read and write operations.

or “ab+”
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

CLOSING A FILE

A file is closed when no more Input/Output operations is to be performed on it.


Closing a file is carried out by using the fclose() library functions.
Syntax:

fclose(fptr);

Example:
FILE *book;
book = fopen(“computer”, ”r”);
.
.
.
fclose(book);

Example Program which opens a file in write mode


#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}

Output
The content of the file will be printed.

Example program to write data to a text file and to read it


#include<stdio.h>
#include<conio.h>
int main( )
{
FILE *fp; int rno , i; float avg;
char name[20] , filename[15];
clrscr();
printf("\nEnter the filename:\n");
scanf("%s",filename);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

fp=fopen(filename,"w");
for(i=1;i<=3;i++)
{
printf("Enter rno,name,average of student no%d:",i);
scanf("%d %s %f",&rno,name,&avg);
fprintf(fp,"%d %s %f\n",rno,name,avg);
}
fclose(fp);

fp=fopen ( filename, "r" );


printf(“The Students details”);
for(i=1;i<=3;i++)
{
fscanf(fp,"%d %s %f",&rno,name,&avg); printf("\n%d %s %f",rno,name,avg);
}
fclose(fp);
getch();
return 0;
}

Output:
Enter the filename:
test.txt
Enter rno,name,average of student no:1 101
ram 75
Enter rno,name,average of student no:2 102
Raj 79.4
Enter rno,name,average of student no:3 103
Rahul 92.3

The Students details 101 ram 75.000000


102 Raj 79.400002
103 Rahul 92.300003

9.FILE INPUT AND OUTPUT FUNCTIONS

There are eight operations on files. They are

1. putc()
2. getc()
3. getw()
4. putw()
5. fscanf()
6. fread()
7. fprintf()
8. fwrite()
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

1. SINGLE CHARACTER INPUT/OUTPUT FUNCTIONS FOR FILES

Once a file is opened, an Input/Output operations is performed on file, source of the


functions which facilitate single character Input/Output for file getc() &
putc().
The single character Input function fgetc() receives a single argument, a file pointer
for the file from which a character is read.

(i) Single character input function - putc()


This function operates on file that is copied in writing mode, which writes a
single character to the file.

Syntax: putc(c,fptr);

(ii) Single character output function - getc()

This function operates on file that is opened in reading mode. Reads a single
character from the file.
Syntax: getc(fptr);

Reads character from file pointed by file pointer fp and displays on it screen. Now
file pointer moves by one character position for every getc() function and returns
EOF (end-of-file). EOF is a constant that indicates the end-of-file reached on a
file. To get character from a file terminating character (^z) is entered.

Example: WRITING TO AND READING FROM A FILE.


#include <stdio.h>
main()

FILE *f1;

char c;

printf("Data Input\n\n");

/* Open the file INPUT */

f1 = fopen("INPUT", "w");

/* Get a character from keyboard */

while((c=getchar()) != EOF)

/* Write a character to INPUT */


Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

putc(c,f1);

/* Close the file INPUT */

fclose(f1);

printf("\nData Output\n\n");

/* Reopen the file INPUT */

f1 = fopen("INPUT","r");

/* Read a character from INPUT*/

while((c=getc(f1)) != EOF)

/* Display a character on screen */

printf("%c",c);

/* Close the file INPUT */

fclose(f1);

Output:

Data Input

This is a program to test the file handling features on this system^Z

Data Output
This is a program to test the file handling features on this system

10.INTEGER ORIENTED FILE INPUT AND OUTPUT FUNCTIONS FOR FILE

putw and getw are integer oriented functions. They are similar to the getc and putc
functions and are used to read and write an integer.
(i) Integer input function - putw()
Syntax: putw(integer, fptr);

This function is used to write integer value on file pointed by file pointer.

(ii) Integer output function - getw()


Reads an integer value from file pointed by file pointer. Returns next integer
from input output stream.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Syntax: getw(fptr);

2. STRING INPUT/OUTPUT FUNCTIONS FOR FILE:


(i) String input function – fgets()
The get(s) function is used to receive a string from the standard input device until a
new line or FOF is encountered.
 Where the variable refers to the previously declared character array.
 The string received by the gets() function may include white space
character.
 The gets() function will terminate only with a new line character.
Note: gets() function can receive data for only one variable.

Syntax: fgets();

gets() function with the argument sachin can receive a string of maximum 20
characters as a single string.
The string may/may not include spaces in between them.

(ii) String output function – fputs()


The puts function is used to display a string at a time in the standard output device
followed by a new character. Puts function accepts only a single argument.

Syntax: int fputs(char *s, fptr);

The puts function with the arguments displays the string in the standard output
device which is received previously by using the gets() function.
3. MIXED DATA I/O FUNCTIONS FOR FILE
The function printf() and scanf() are used for performing Input/Output operations
in the file (Without involving file). Similar to scanf() and printf() functions.
(i) File input function -fscanf()
fscanf() is used to perform input operations in files.

fscanf() SYNTAX: fscanf(fptr, ”format_string”, list_of_arguments);


Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Example fscanf(fptr, ”%s %d %s”, &empname, &empno,


&deptname);

(ii) File output function -fprintf()


fprintf() is used to perform Output operations in files.

fprintf() SYNTAX: fprintf(fptr, ”format_string”, list_of_arguments);

Example fprintf(fptr, ”%d %s”, empno, empname);

Example Program to Display the Contents Of The File On The Monitor

Screen

#include<stdio.h>

void main()

FILE *fp; char

ch;

printf("\n\tDISPLAY THE CONTENTS OF THE FILE ON THE MONITOR


SCREEN");

printf("\n\t*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

*"); fp=fopen("textfile.txt","w");

if(fp==NULL)

printf("\nError in file opening");

else

printf("\nEnter characters [press ctrl+z to exit]:");

while((ch=getchar())!=EOF)

putc(ch,fp);

}
printf("\nFile Content saved in textfile.txt");
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

fclose(fp);

fp=fopen("textfile.txt","r");

printf("\n The content read from file and display on the screen");

printf("\n \n");

while((ch=getc(fp))!=EOF)

printf("%c",ch);

fclose(fp);

getch();

Output:

DISPLAY THE CONTENTS OF THE FILE ON THE MONITOR SCREEN

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Enter characters [press ctrl+z to exit]:The Expansion of computer is


Commonly Operated Machine Particulary Used for Technology and Educational
Research^Z

^Z

File Content saved in textfile.txt

The content read from file and display on the screen

The Expansion of computer is Commonly Operated Machine Particulary Used for


Technology and Educational Research

4. UNFORMATTED READ AND WRITE FUNCTIONS

The fread() and fwrite() functions


The fread() and fwrite() functions often referred to as unformatted read and write
functions. Similarly, files of this type are often referred to as unformatted files.
The fread() function is used for reading an entire block from a given file. The
fwrite() function is used for writing an entire structure block to a given file.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

fread() - This function reads data from stream of any data type.

Syntax
size_t fread(void *ptr, size_t size,size_t n, FILE *fp);

size_t used for memory objects and repeats count.

fwrite()
This function writes to a stream or specified file. The syntax for fwrite() is

Syntax
size_t fwrite(const void *ptr,size_t size,size_t n,FILE *fp);

where n is the number of elements written to that file.

11.ERROR HANDLING WHILE READING AND WRITING FILES

The incorrect reading and writing situation are listed below:

1. Reading a file beyond the end-of-file (EOF).


2. Accessing a file that has not been opened.
3. Opening a file with the invalid filename.
4. Reading a file that is opened in write mode.
5. Writing on a file that is opened in read mode.
6. Tyring to write to a file which is write-protected one.
7. Closing a file that is not opened.

The feof() function:

The feof() function is used to check whether the file pointer is at the end-of-
file or not. It takes the file pointer as the argument and returns non-zero if the
file pointer is at the end-of- file. Otherwise it returns zero.

The ferror() function:

The ferror() function reports the status of the file indicated. It also takes a FILE
pointer as its only argument and returns a non zero integer if an error has been
detected up to that point, during processing. It returns zero otherwise.

12.RANDOM ACCESS TO FILES

Sequential Files are generally used in cases where the program processes the data
in a sequential fashion.
Eg: counting words in a text file
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Random Access File functions

To access a particular part of a file randomly and not in reading the other parts.
This is done by using the I/O library functions, namely
1. fseek()
2. ftell()
3. rewind()
4. fseek() FUNCTION

The fseek() function allows us to read from or write to any point in the stream of
bytes opened by using the fopen() function. It is used to move the position of the
file pointer to the desired location in the file.

1. fseek() FUNCTION

The fseek() function allows us to read from or write to any point in the stream of
bytes opened by using the fopen() function. It is used to move the position of the
file pointer to the desired location in the file.

Syntax fseek(fptr, offset, position)

Description fptr – file pointer of the file to be accessed.

offset – is a negative or positive number or a variable of long


integer data type to reposition the file pointer towards the
backward or forward direction from the location specified by
position.

position – Current position of the file pointer.


Example: Beginning

fseek(fptr,5L,0)
;

5 byte

2. ftell() FUNCTION
Function returns the current position of the file pointer in the file.
Syntax

long int ftell(fptr);


Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Example

a = ftell(fptr);  Returns the size of the


file in bytes to the variable a.

3. rewind() FUNCTION
Function resets the file pointer to the beginning of the file.

Syntax

rewind(fptr);

Example Program that uses the functions ftell and fseek.

A program employing ftell and fseek functions is shown. We have created a


file RANDOM with the following contents:

Position ----> 0 1 2 ..................... 25

Character

stored ----> A B C ............................................... Z


(ILLUSTRATION OF fseek & ftell FUNCTIONS)
#include <stdio.h>
main()
{

FILE *fp; long n;


char c;
fp = fopen("RANDOM", "w");
while((c = getchar()) != EOF)
putc(c,fp);
printf("No. of characters entered = %ld\n", ftell(fp));
fclose(fp);
fp = fopen("RANDOM","r"); n =
0L;

while(feof(fp) == 0)

fseek(fp, n, 0); /* Position to (n+1)th character


*/ printf("Position of %c is %ld\n", getc(fp),ftell(fp));
n = n+5L;
}
putchar('\n');
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

fseek(fp,-1L,2); /* Position to the last character */


do
{

putchar(getc(fp));

while(!fseek(fp,-2L,1));
fclose(fp);
}

Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z

No. of characters entered = 26


Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
Position of is 30

ZYXWVUTSRQPONMLKJIHGFEDCBA

13.COMMAND LINE ARGUMENTS


An executable program that performs a specific task for operating system is
called as
command.
The commands are issued from the prompt of operating system, some arguments
are associated with the commands, and hence these arguments are called as
command line arguments.

The main() function receives two arguments and they are

1. argc
2. argv

1. Argument argc

An argument argc counts total number of arguments passed from command


prompt. It returns a value which is equal to total number of arguments passed
through main().
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

2. Argument argv

It is a pointer to an array of character strings which contains names of


arguments. Each word is an argument.

int main ( int argc, char *argv[] )

Command line argument is a parameter supplied to a program when the


program is invoked. This parameter represents filename of the program that
should process.

In general, execution of C program starts from main() function. It has two


arguments like argc and argv. The argc is an argument counter that counts
the number of arguments on the command line. The argv is an argument
vector. It represents an array of character pointer that point to command line
arguments.

The size of the array will be equal to the value of argc. Information contained
in command line is passed to program through these arguments whenever
main is called. The first parameter in command line is program name. Here
argv[0] represents the program name.

To access command line arguments, declare the main function and


parameter as
main(int argc, char *argv[ ])
{
……..
}

Program to Sum of integers using command line arguments


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main(int argc , char *argv[])
{
int i,sum=0;
clrscr();
printf("\n\tSUM OF INTEGERS USING COMMAND LINE ARGUMENT");

printf("\n\t*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
if(argc<3)
{
printf("\nAtleast Type 2 Numbers");
exit(1);
}
printf("\nThe sum is : ");
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

for(i=1;i<argc;i++)
sum = sum + atoi(argv[i]);
printf("%d",sum);
}

Program to copy the content of one file to another file using command line
arguments
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
FILE *fp1,*fp2;
int i,ch;
if(argc!=3)
{
printf("Program parameter missing");
exit(0);
}
fp1=fopen(argv[1],"r");
fp2=fopen(argv[2],"a");
while((ch=getc(fp1))!=EOF)
putc(ch,fp2);
printf("file %s is successfully copied",argv[1]);
Return(0);
}

14.PREPROCESSOR

Definition
The Preprocessor, as the name implies, is a program that processes the
source code before it passes through the complier. This is known as
preprocessor.

Important Points
• It operates under the control of preprocessor command lines or directives.
• Preprocessor directives are placed in the source program before the main line.
• Before the source code passes through the compiler, it is examined by the
preprocessor for any preprocessor directives.
• Preprocessor directives begin with the symbol # in column one and do not
require a semicolon at the end.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Three Categories
i. Macro substitution directives
ii. File Inclusion directives
iii. Compiler control directives (or) Conditional inclusion directives

(i) Macro Substitution directive


It is also called as #define preprocessor directives. The working manner is,
simply removes the occurrences of the constant and replaces them using the
expression

Syntax
The general form is
#define identifier string

Examples
Simple Macro Sub for Expressions
#define AREA 5 * 12.46
#define SIZE sizeof(int) * 7
#define TWO-PI 2.0 * 3.14
#define A (55 – 33)
#define B (55 + 33)

Simple Macro Sub for Creating C Sentences


#define TEST if (x>y)
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

#define AND
#define PRINT printf(“Success”);
Note: The above statements are consider as, TEST AND PRINT
That will become
if (x>y) printf (“Success \n”);

Simple Macro Sub for Replacing Tokens


#define EQALS ==
#define AND &&
#define OR ||
#define NOT-EQUAL !=
#define START {
#define END }
#define BLANK_LINE printf(“\n”);
#define INCREMENT ++

Macros With Arguments


 More complex and more useful form of replacement
 #define identifier(f1,f2,…..,fn) string
 No space between id and the left (
 Subsequent occurrence of a macro with arguments is known as a macro
call
 When macro is called, the preprocessor substitutes replacing formal with
actual parameters

A Simple Example of Macros With Arguments (MWA)


#define CUBE(x) (x*x*x)
volume = CUBE (side) // (side * side * side)
volume = CUBE (a + b) would expand to
volume = (a + b * a + b * a + b)
Explanation:
#define CUBE (x) ( (x) * (x) * (x) )is a correct definition, which expands to
volume = ((a +b) * (a + b) * (a + b))

Program
#include<stdio.h>
#define PIE 3.14
main()
{
float r=3,area;
area=2*r*PIE;
printf(“%f”,area);
getch();
}

(ii) File Inclusion directive


This is achieved by
#include “filename
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

or

#include <filename>

Example
#include <stdio.h>
#include “TEST.C”

(iii) Compiler control directives (or) Conditional inclusion


These are the directives meant for controlling the compiler actions. C
preprocessor offers a feature known as conditional compilation, which can be used
to switch off or on a particular line or group of lines in a program.
Mostly #ifdef and #ifndef are used in these directives.

Rules for defining Preprocessor


• Every preprocessor must start with # symbol.
• The preprocessor is always placed before main() function.
• The preprocessor cannot have termination with semicolon.
• There is no assignment operator in #define statement.
• The conditional macro must be terminated (#ifdef, #endif).

Predefined Macros
ANSI C defines a number of macros. Although each one is available for your use in
programming, the predefined macros should not be directly modified.

Macro Description

DATE The current date as a character literal in "MMM DD YYYY"


format
TIME The current time as a character literal in "HH:MM:SS" format

FILE This contains the current filename as a string literal.

LINE This contains the current line number as a decimal constant.

STDC Defined as 1 when the compiler complies with the ANSI


standard.

Example
#include <stdio.h>
main()
{
printf("File :%s\n", FILE;
printf("Date :%s\n", DATE );
printf("Time :%s\n", TIME);
printf("Line :%d\n", LINE );
printf("ANSI :%d\n", STDC);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Note: The above program is saved in sample.c

Output
File :C:\Users\Documents\sample.c Date :Aug 5 2015
Time :19:03:18
Line :7
ANSI :1

15.MISCELLANEOUS DIRECTIVES:
There are two more pre-processor directives, though they are not very commonly
used.
They are #undef and #pragma

1. #undef
On some occasion, it may b desirable to cause a defined name to become
„undefined‟. This can be accomplished by means of the 3undef directive.

Eg: #undef PENTIUM

would cause the definition of PENTUM to be removed from the system. All
subsequent #ifdef PENTUM statements became false.

#include<stdio.h>
#define height 100
void main()
{

printf (“First defined height value: %d”,height);


#undef height
//undefined variable
#define height 700//redefining the same for new value
printf(“Height value after redefining %d”,height );

Output
First defined count value:100
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Sl Pragma Description
. command
n
o
1. #pragma startup This directive executes function named
“function_name_1”before starting of the program
<function_name_1
>
2. #pragma exit This directive executes function named
<function_name_2 “function_name_2”before termination of
> the program
3. #pragma warn-rvl If function doesn‟t return a value, then
warnings are suppressed by this directive while
compiling.
4. #pragma warm-par If function doesn‟t use passed function
parameter, then warnings are suppressed.
5. #pragma warn-rch If non-reachable code is written inside a
program, such warnings are suppressed by this
directive.
Height value after redefining:700
2. #pragma
A special directive we can turn on or off certain features. Pragma vary from
one compiles to another.

The following table shows list of programmer command.

Example Program
#include<stdio.h>
int display();
#pragma startup display
#pragma exit display
int main()
{ printf("\nI am in main function");
return 0;
}
int display()
{
printf("\nI am in display function");
return 0;
}

Output:
Enter the filename:
test.txt
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C

Enter rno,name,average of student no:1 101


ram 75
Enter rno,name,average of student no:2 102
raj 79.4
Enter rno,name,average of student no:3 103
rahul 92.3
The Students details
101 ram 75.000000
102 raj 79.400002
103 rahul 92.300003

You might also like