CPNM Unit 5 & 6 Structures & Files
CPNM Unit 5 & 6 Structures & Files
UNIT-V, VI
STRUCTURES, UNIONS & FIlES
Frequently Asked Questions
Files:
Structures
3
Let us examine these two approaches one by one.. Let us begin with a program that uses Arrays.
#include<stdio.h>
void main( )
{
char name[3] ;
float price[3] ;
int pages[3], i ;
printf ( "\nEnter names, prices and no. of pages of 3 books\n"
) ;
for ( i = 0 ; i <= 2 ; i++ )
scanf ( "%c %f %d", &name[i], &price[i], &pages[i] );
printf ( "\nAnd this is what you entered\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "%c %f %d\n", name[i], price[i], pages[i] );
}
Output:
Enter names, prices and no. of pages of 3 book And
this is what you entered
A 100.00 354 A 100.000000 354
C 256.50 682 C 256.500000 682
F 233.70 512 F 233.700000 512
This approach no doubt allows you to store names, prices and number of pages. But as you must
have realized, it is an unwieldy approach that obscures the fact that you are dealing with a group
of characteristics related to a single entity—the book.
4
The program becomes more difficult to handle as the number of items relating to the book go
on increasing. For example, we would be required to use a number of arrays, if we also decide
to store name of the publisher, date of purchase of book, etc. To solve this problem, C provides
a special data type—the structure.
Defining Structure
Syntax of structure declaration:
struct structure name
{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
……………
datatypen var1,var2,…;
};
➢ The struct keyword is used to declare structures.
➢ The keyword struct identifies the beginning of a structure definition.
➢ It's followed by a structure name or tag that is the name given to the structure.
➢ Following the tag are the structure members, enclosed in braces.
➢ A structure can contain any of C's data types, including arrays and other structures.
➢ Each variable within a structure is called a member of the structure.
➢ The above structure declaration is also known as template.
➢ The template is terminated with semicolon (;).
Examples:
1.Define a structure by name student which includes student name,roll number and marks.
struct student
{
char name [10];
int rno;
float marks ;
} ;
This statement defines a new data type called struct student.
2. Define a structure by name book which includes name of the book, price and number of
pages.
struct book
{
char name ;
float price ;
int pages ;} ;
This statement defines a new data type called struct book.
5
After defining the structure, variables for that structure are to be declared to access the
members of structures.
Syntax for declaration of structure variable is
struct structurename var1,var2,var3,……varn;
Example: struct book b1, b2, b3 ;
The variables b1, b2, b3 are variables of the type struct book.
The memory is allocated for structures only after the declaration of structure variable. The
memory allocated is equal to the sum of memory required by all the members in structure
definition.
Example :
struct book b1, b2, b3 ;
This statement assigns space in memory for b1,b2,b3. It allocates space to hold all the
elements in the structure—in this case, 7 bytes—one for name, four for price and two for
pages. These bytes are always in adjacent memory locations.
Example:
struct student
{
char name [10];
int rno;
float marks ;
} ;
struct student s1,s2;
The above declaration allocates 16 bytes(10 bytes for name,2 bytes for roll number and 4
bytes for marks) for s1 and 16 bytes for s2.
The variables for structure can be declared in three different ways:
method 1:
struct structure name
{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
……………
……………
datatypen var1,var2,…; };
struct structurename var1,var2,var3,……varn;
method 2:
struct structure name
6
{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
…………… .
……………
datatypen var1,var2,…;
}var1,var2,var3,…..varn;
method3:
struct
{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
…………… .
……………
datatypen var1,var2,…;
}var1,var2,var3,…..varn;
The method 3 cannot be used for future declaration of variables as structure tag is not present.
Note: The use of structure tag is optional in C language.
For example,Variables for structure book are declared in 3 different ways
1. struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;
2.struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
3. struct
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
7
So to refer to pages of the structure defined in our structure book example we have to use,
b1.pages
Similarly, to refer to price we would use,
b1.price.
Structure Initialization
Like primary variables and arrays, structure variables can also be initialized where they are
declared.
here the values should be assigned in the same order of declaration of the members in the
definition.
example:
struct book
{
char name[10] ;
float price ;
int pages ;
} ;
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;
Examples:
1. Define a structure by name student which includes student name,roll number and marks.
struct student
{
char name[10];
int rno;
8
float marks ;
} ;
This statement defines a new data type called struct student.
2. Define a structure by name book which includes name of the book ,price and number of
pages.
struct book
{
char name[10];
float price;
int pages ;
} ;
This statement defines a new data type called struct book.
Whatever be the elements of a structure, they are always stored in contiguous memory locations.
The following program would illustrate this:
/* Memory map of structure elements */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
Actually the structure elements are stored in memory as shown in the Figure below
B 130.00 550
Array:
▪ Array is a derived data type.
▪ It allocates memory only for the elements of the subscripts. Array allocates static
memory and uses index / subscript for accessing elements of the array.
▪ It allocates memory of same files that is if we declare integer type array then it allocates
2 byte memory for each cell.
▪ It does not contain structure within itself.
▪ It can contain only homogeneous data types.
▪ Array is a pointer to the first element of it
▪ We can access the array by using index number.
▪ The elements of the array are contiguous in memory
▪ Array element access takes less time in comparison with structures.
Structure:
▪ Structure is a programmer or user - defined data type.
▪ It does not allocate memory till the elements of the structure are accessed. Structures
allocate dynamic memory and uses (.) operator for accessing the member of a structure.
▪ It allocates the memory for the highest data type.
▪ It contain array within itself.
▪ It can contain only non-homogeneous data types.
▪ Structure is not a pointer
▪ The elements of structure are accessed by using dot (.) operator with structure reference
name.
▪ The elements of a structure may not be contiguous.
Sample Program
Define a structure for student which include roll number ,name,age and marks .
Write a program to read and display the information of 3 students.
#include<stdio.h>
#include<string.h>
struct student
10
{
int rno;
char name[10];
int marks,age;
};
void main()
{
//assigning values to structure variable s1 using initialization
struct student s1={2,"Gandhi",89,18};
struct student s2,s3;
//assigning values to s2 using assignment operator.
s2.rno=5;
s2.marks=90;
s2.age=18;
strcpy(s2.name,"Ram ");
//reading values for s3 using standard input function.
printf("\n enter rno,name ,marks,age of student: ");
scanf("%d%s%d%d",&s3.rno,s3.name,&s3.marks,&s3.age);
printf("\n\n");
printf("Details of student 1:\n");
printf("\n roll number: %d",s1.rno);
printf("\n name :%s",s1.name);
printf("\n marks: %d",s1.marks);
printf("\n age: %d",s1.age);
printf("\n\n");
printf("Details of student 2:\n");
printf("\n roll number: %d",s2.rno);
printf("\n name :%s",s2.name);
printf("\n marks: %d",s2.marks);
printf("\n age: %d",s2.age);
printf("\n\n");
printf("Details of student 3:\n");
printf("\n roll number: %d",s3.rno);
printf("\n name :%s",s3.name);
printf("\n marks: %d",s3.marks);
printf("\n age: %d",s3.age);
}
output :
enter rno,name,marks,age of student:1
Raju
92
18
11
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18
Details of student 2:
roll number: 5
name :Ram
marks :90
age: 18
Details of student 3:
roll number: 1
name :Raju
marks :92
age: 18
The only operation that is allowed on structure variables is assignment operation. Two
variables of same structure can be copied similar to ordinary variables.
If P1 and P2 are variables of struct P, then P1 values can be assigned to P2 as
P2=P1;
where values of P1 will be assigned to P2 member by member.
#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
{
//assigning values to structure variable s1 using initalization
struct student s1={2,"Gandhi",89,18};
struct student s2;
s2=s1;
printf("\nDetails of student 1:\n");
12
Details of student 2:
roll number: 2
name :Gandhi
marks :89
age: 18
#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
13
int marks,age;
};
void main()
{
int m;
//assigning values to structure variable s1 using initalization
struct student s1={2,"Gandhi",89,18};
struct student s2;
s2=s1;
printf("\nDetails of student 1:\n");
printf("\n roll number: %d",s1.rno);
printf("\n name :%s",s1.name);
printf("\n marks: %d",s1.marks);
printf("\n age: %d",s1.age);
printf("\n\n");
printf("Details of student 2:\n");
printf("\n roll number: %d",s2.rno);
printf("\n name :%s",s2.name);
printf("\n marks: %d",s2.marks);
printf("\n age: %d",s2.age);
output:
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18
Details of student 2:
roll number: 2
name :Gandhi
marks :89
age: 18
both the details are same
14
Array Of Structures
struct struct-name
{
datatype var1;
datatype var2;
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
Program:
Define a structure for student which include roll number ,name,age and marks .
Write a program to read and display the information of ‘n’ number of students where n is
value supplied by user.
#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
15
{
struct student s[10];//Declares array of 10 student.
int i,n;
printf("\n enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
//reading values for s3 using standard input function.
printf("\n enter rno,name ,marks,age of student %d: ",i+1);
scanf("%d%s%d%d",&s[i].rno,s[i].name,&s[i].marks,&s[i].age);
}
printf("\n\n");
printf("Details of students are :\n");
for(i=0;i<n;i++)
{
printf("\n Details of student %d:\n",i+1);
printf("\n roll number: %d",s[i].rno);
printf("\n name :%s",s[i].name);
printf("\n marks: %d",s[i].marks);
printf("\n age: %d",s[i].age);
}
}
Output:
enter number of students :3
enter rno,name,marks,age of student 1:2
Gandhi
89
18
enter rno,name,marks,age of student 2:5
Raj
76
18
enter rno,name,marks,age of student 3:6
Ram
86
18
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18
Details of student 2:
16
roll number: 5
name :Raj
marks :76
age: 18
Details of student 3:
roll number: 6
name :Ram
marks :86
age: 18
In the above program the memory allocated for structure variable is 160 bytes consecutively
in which first 16 bytes for 1st student 1(s[0]),next 16 bytes for
2nd student 2(s[1]) and so on last 16 bytes for 10 th student (s[9]).
The following figure shows the memory allocation for array of structures.
16bytes 16 16 16 16 16 16 16 16 16
s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
As we know, structure is collection of different data type. Like normal data type, It can also
store an array as well.
In arrays within structure the member of structure is array.
Syntax for array within structure
struct struct-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
17
struct Student
{
int Roll;
char Name[10];
int Marks[3]; //array of marks
int Total;
float Avg;
};
void main()
{
int i;
struct Student S;
S.Total = 0;
for(i=0;i<3;i++)
{
printf("\n\nEnter Marks %d : ",i+1);
scanf("%d",&S.Marks[i]);
S.Avg = S.Total / 3;
printf("\nRoll : %d",S.Roll);
printf("\nName : %s",S.Name);
printf("\nTotal : %d",S.Total);
printf("\nAverage : %f",S.Avg);
}
Output :
Enter Student Roll : 4
Enter Student Name : GANDHI
18
Enter marks 1 : 80
Enter marks 2 : 90
Enter marks 3 : 75
Roll : 4
Name : GANDHI
Total : 245
Average : 81.000000
The memory allocated for structure variable s is 24 bytes(2-roll,10-name,6-marks,2-total,4-
avg).
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
19
int main()
{
struct student_detail stu_data = {1, "Raju",
90.5, 71145,"GITAM University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n",
stu_data.percentage);
struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};
struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};
void main()
20
{
int i;
struct Employee E;
printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployeeHouseNo : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployeeHouseNo : %s",E.Add.PinCode);
Output :
Details of Employees
Employee Id : 101
21
UNIONS
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.
Defining a Union:
To define a union, you must use the union statement in the same way as you did while defining
a structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows –
The union tag is optional and 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, you can specify one or more union variables but it is optional. Here is the
way you would define a union type named Data having three members i, f, and str –
union Data {
int i;
float f;
char str[20];
} d;
Now, a variable of ‘d’ type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string.
The following example displays the total memory size occupied by the above union −
Example Program:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data d;
printf( "Memory size occupied by data : %d\n", sizeof(d));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by d: 20
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
24
OUTPUT:
We can’t access all members in union at same time but structure can do that.
25
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
Here, all the members are getting printed very well because one member is being used at a time.
Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
26
4. The address of each member will be in 4. The address is same for all the members of
ascending order This indicates that memory a union. This indicates that every member
for each member will start at different offset begins at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member
affect other members of the structure. will alter other member values.
6. Individual Structure member can be 6. Only one Union member can be accessed
accessed at a time at a time.
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
27
size of union = 32
size of structure = 40
But, the memory required to store a union variable is the memory required for the largest
element of a union.
#include<stdio.h>
struct number1
{
int i;
float f;
char c;
}sn;
28
union number2
{
int i;
float f;
char c;
}un;
void main()
{
printf("Details of structure\n");
printf("size of structure number1=%d\n",sizeof(sn));
sn.i=10;
sn.f=89.00;
sn.c='X';
printf("sn.i=%d\n sn.f=%f\n sn.c=%c\n",sn.i,sn.f,sn.c);
printf("Details of Union\n");
printf("size of Union number2=%d\n",sizeof(un));
un.i=10;
un.f=89.00;
un.c='X';
printf("un.i=%d\n un.f=%f\n un.c=%c\n",un.i,un.f,un.c);
}
Output:
size of structure number1= 7
sn.i =10
sn.f =89.00
sn.c =X
size of Union number2 = 4
un.i =Garbage value
un.f = Garbage value
un.c =X
#include <stdio.h>
#include <string.h>
union Data {
29
int ID;
float sal;
char name20];
};
int main( ) {
union Data d1,d2;
d1.sal=50000;
d2.sal=60000;
FILES
Definition:
FILE is a predefined structure data type which is defined in library file called stdio.h.
30
(OR)
FILE is a set of records that can be accessed through a set of library functions.
Syntax:
FILE *filepointerobject;
Example:
FILE *fp; // where FILE is a keyword and “fp” is a file pointer object
C supports a number of functions that have the ability to perform basic file operations,
which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
fopen() is a predefined file handling function which is used to open already existing file or to
create a file. It accepts two strings, the first is the name of the file, and the second is the mode
in which it should be opened. The general format of the function used for opening a file is as
follows:
Syntax:
FILE *filepointer;
filepointer=fopen(“filename.filetype”,”mode”);
Note: The function fopen( ) is compulsory for the files to do any operations, without
fopen( ), we cannot perform operations on files.
6. “a+” Open for reading and appending. If file is not existing the file is
created.
B) If you mention the path in fopen( ) function, then the new file will be saved in that
particular path. Path should be mentioned as follows:
Example: fp=fopen(“d:\\gitam\\hello.txt”, “w”);
(Or)
fp=fopen(“d:/gitam/hello.txt”, “w”);
Where fp id is a file pointer associated with a file that has been opened for writing. The control
string is file output specifications list may include variable, constant and string.
This statement would cause the reading of items in the control string.
Where fp id is a file pointer associated with a file that has been opened for reading. The control
string is file output specifications list may include variable, constant and string.
➢ When we have finished reading from the file, we need to close it. This is done using the
function fclose through the statement, fclose( fp );
➢ During a write to a file, the data written is not put on the disk immediately. It is stored
in a buffer. When the buffer is full, all its contents are actually written to the disk. The
process of emptying the buffer by writing its contents to disk is called flushing the
buffer.
➢ Closing the file flushes the buffer and releases the space taken by the FILE structure
which is returned by fopen. Operating System normally imposes a limit on the number
of files that can be opened by a process at a time. Hence, closing a file means that
another can be opened in its place. Hence, if a particular FILE pointer is not required
after a certain point in a program, pass it to fclose and close the file.
Syntax: fclose(filepointer);
Example: fclose(fp); // Where fp is a file pointer
Example Program1 using write mode to create new file and to write the data in
file:
#include<stdio.h>
void main(){
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","w");
printf("Input an integer");
scanf("%d",&i);
printf("Enter your name:");
scanf("%s",name);
fprintf(fp,"%d\n%s",i,name);
fclose(fp);
}
Output:
Input an intiger5
Enter ur name:gitam
34
Data1.txt
5
gitam
Example Program2 using read mode to read the data from file:
#include<stdio.h>
void main() {
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","r");
fscanf(fp,"%d%s",&i,name);
printf("The integer in data1.txt is %d\n",i);
printf("The String in data1.txt is %s",name);
fclose(fp);
}
Output:
The integer in data1.txt is 5
The String in data1.txt is gitam
Example Program3 using append mode to add the data in the existing file:
#include<stdio.h>
void main() {
char name[15];
FILE *fp;
fp=fopen("data2.txt","a");
printf("Enter ur name:");
scanf("%s",name);
fprintf(fp,"%s",name);
fclose(fp);
fp=fopen("data2.txt","r");
if(fscanf(fp,"%s",name))
printf("%s",name);
fclose(fp);
}
35
Output:
Enter ur name:GITAM
GITAM
In data2.txt
GITAM
FILE STRUCTURE:
I/O functions available are similar to their console counterparts; scanf becomes fscanf, printf
becomes fprintf, etc., These functions read and write from file streams. As an example, the file
stream structure FILE defined in the header file stdio.h in DOS is shown below:
typedef struct
{
int level; /* fill/empty level of buffer */
usigned flags; /* File status flags */
char fd; /* File descriptor (handle) */
unsigned char hold; /* Ungetc char if no buffer */
int bsize; /* Buffer size */
unsigned char _FAR *buffer; /* Data transfer buffer */
unsigned char _FAR *curp;/* Current active pointer */
unsigned istemp; /* Temporary file indicator */
short token; /* Used for validity checking */
} FILE; /* This is the FILE Object *
NOTE: FILE is defined as New Structure Data Type in the stdio.h file as shown in above
method.
End Of File:
to enter more than one "file" into a terminal, so a key sequence is reserved to indicate
end of input.
✓ Cntrl+Z is the key in DOS to end or terminate the input values.
✓ Cntrl+D is the key in UNIX to end or terminate the input values.
Output:
Enter the Text:
Use Ctrl+z to stop entry
Hi Raju...
how r u... how is ur studies...:-)
^Z // Cntrl+Z key terminated the input
values
We having various kinds of File Handling Functions, as some of them are discussed in previous
notes and remaining we can discuss now…
✓ fgetc( ) or getc( ) is a predefined file handling function which is used to read a single
character from a existing file opened in read(“r”) mode by fopen( ), which is same as
like getchar( ) function.
Syntax:
ch_var= fgetc(filepointer); (Or) ch_var=getc(filepointer);
✓ getc( ) or fgetc( ) gets the next character from the input file to which the file pointer fp
points to. The function getc( ) will return an end-of-file(EOF) marker when the end of
the file has been reached or it if encounters an error.
✓ On Success the function fputc( ) or putc( ) will return the value that it has written to the
file, otherwise it returns EOF.
while((ch=getc(fp))!=EOF)*/
printf("%c",ch);
fclose(fp);
}
Output:
Text from file is:
Hi Raju... how r u... how is ur studies...:-)
✓ fputc( ) or putc( ) is a predefined file handling function which is used to print a single
character in a new file opened in write(“w”) mode by fopen( ), which is same as like
putchar( ) function.
Syntax:
fputc(ch_var , filepointer); (Or) putc(ch_var , filepointer);
Example:
/* A program to Write a Character in a file and read a Character from a file */
#include<stdio.h>
main( ){
FILE *fp;
char ch;
fp=fopen("DATA1.txt","w");
Output:
Enter the Text:
Use Ctrl+z to stop entry
Hi ...
how are you... how is your studies...:-)
^Z // Cntrl+Z key terminated the input
values
✓ fgets( ) is a predefined file handling function which is used to read a line of text from an
existing file opened in read(“r”) mode by fopen( ), which is same as like gets( ) function.
✓ The function fgets( ) read character from the stream fp into the character array ‘ch’ until a
newline character is read, or end-of-file is reached. It then appends the terminating null
character after the last character read and returns ‘ch’ if end-of-file occurs before reading
any character an error occurs during input fgets( ) returns NULL.
✓ fputs( ) is a predefined file handling function which is used to print a string in a new file
opened in write(“w”) mode by fopen( ), which is same as like puts( ) function.
General Format:
Int fputs(const char *s, FILE *fp);
Syntax:
fputs(ch_var , filepointer);
Example:
char ch[10]=”gitam”;
fputs(ch, fp);
Where ‘ch’ is a string variable.
Where ‘fp’ is a file pointer object.
The function fputs( ) writes to the stream fp except the terminating null character of string s, it
returns EOF if an error occurs during output otherwise it returns a non negative value.
The getw( ) and putw( ) are predefined file handling integer-oriented functions. They are
similar to the getc( ) and putc( ) functions and are used to read and write integer values.
These functions would be useful when we deal with only integer data. The general forms
of getw and putw are:
Example: /* A program to Write and Read only one Integer Value in a file */
#include<stdio.h>
main()
{ int n,m;
FILE *fp=fopen("num.txt","w");
puts("Enter a number:");
scanf("%d",&n);
putw(n,fp); /* printing only integer value in a file */
fclose(fp);
fp=fopen("num.txt","r");
m=getw(fp); /* reading only integer value from a file */
printf("From File int val=%d",m);
}
Output1:
Enter a number: 16
From File int val=16
Output2:
Enter a number: 25 35 45
From File int val=25 /* here it take only one value,
basing on program requirement */
Output3:
Enter a number: 25.5
Frm File int val=25
Output4:
Enter a number: A
Frm File int val=28056 /* here it doesn’t print ASCII value
of ‘A’, it just print some-garbage value */
main()
{ int n,m;
FILE *fp=fopen("num.txt","w");
puts(“Press Cntl+Z to end the values”);
puts("Enter the numbers:");
while(scanf("%d",&n)!=EOF)
putw(n,fp);
fclose(fp);
fp=fopen("num.txt","r");
puts(“Entered values in file are:”);
while((m=getw(fp))!=EOF)
printf("%d\n",m);
}
Output:
Press Cntl+Z to end the values
Enter the numbers:
1 2 10 20 30 45
^Z
Entered values in file are:
1
2
10
20
30
45
/* File program to read a character file and encrypts it by
replacing each alphabet by its next alphabet cyclically i.e., z
is replaced by a. Non-alphabets in the file are retained as they
are. Write the encrypted text into another file */
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp1,*fp2;
char fname1[20],fname2[20];
char ch1,ch2;
printf("Enter the source file name ");
scanf("%s",fname1);
fp1=fopen(fname1,"r");
if(fp1==NULL)
44
fp2=fopen(fname2,"w");
while((ch1=fgetc(fp1))!=EOF)
{
printf("%c",ch1);
if((ch1>=65 && ch1<=89) || (ch1>=97 && ch1<=121))
ch2=ch1+1;
else if(ch1==90 || ch1==122)
ch2=ch1-25;
else
ch2=ch1;
fputc(ch2,fp2);
}
printf("File copied into %s succesfull",fname2);
fclose(fp1);
fclose(fp2);
}
}
Output:
Output
Computer i
46
#include<stdio.h>
main()
{
FILE *fp;
int s=0,b=0;
char c;
fp=fopen(“fib.c”,”r”);
while((c=getc(fp))!=EOF)
{
if(c==’;’)
s++;
if(c==’{‘)
b++;
}
fclose(fp);
printf(“\t\n number of statement terminators=%d”,s);
printf(“\t\n no of opening braces=%d”,b);
}
Output :
Number of Statements terminators=10
No.of Opening braces=3
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
47
char s;
fp1=fopen(“input.txt”,”r”);
fp2=fopen(“output.txt”,”w”);
while ((s=getc(fp1))!=EOF)
putc(s,fp2);
fclose(fp1);
fclose(fp2);
}
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp1,*fp2;
char s,c;
clrscr();
printf("\n\n\t one.txt contents are \n\n");
/*prints contents of file1 on monitor*/
fp1=fopen("one.txt","r");
while((c=getc(fp1))!=EOF)
printf("%c",c);
fclose(fp1);
printf("\n\n\t two.txt contents before appending are \n\n");
/*prints contents of file2 on monitor before appending*/
48
fp2=fopen("two.txt","r");
while((c=getc(fp2))!=EOF)
printf("%c",c);
fclose(fp2);
/*appends contents of file1 to file2*/
fp1=fopen("one.txt","r");
fp2=fopen("two.txt","a");
while((c=getc(fp1))!=EOF)
putc(c,fp2);
fcloseall();
printf("\n\n\t two.txt contents after appending are \n\n");
/*prints contents of file2 on monitor after appending*/
fp2=fopen("two.txt","r");
while((c=getc(fp2))!=EOF)
printf("%c",c);
fclose(fp2);
}
Output:
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("text.txt","r");
49
fp2=fopen("copy.txt","w");
while((c=getc(fp1))!=EOF)
{
if(c>=65&&c<=91)
c=c+32;
else
c=c-32;
putc(c,fp2);
}
fcloseall();
}
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp,*fp1,*fp2;
int c,i;
clrscr();
fp=fopen("data.txt","w");
printf("enter the numbers");
for(i=0;i<10;i++)
{
scanf("%d",&c);
putw(c,fp);
}
fclose(fp);
50
fp=fopen("data.txt","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");
while((c=getw(fp))!=EOF)
{
if(c%2==0)
putw(c,fp1);
else
putw(c,fp2);
}
fclose(fp);
fclose(fp1);
fclose(fp2);
fp1=fopen("even.txt","r");
while((c=getw(fp1))!=EOF)
printf("%4d",c);
printf("\n\n");
fp2=fopen("odd.txt","r");
while((c=getw(fp2))!=EOF)
printf("%4d",c);
fcloseall();
}
Output:
Enter the numbers 1 2 3 4 5 6 7 8 9 10
Enter the numbers 1 2 3 4 5 6 7 8 9 10
2 4 6 8 10
1 3 5 7 9