Mod 4 Cs Anu
Mod 4 Cs Anu
Mod 4 Cs Anu
Module 4 STRUCTURES
Basic of structures, structures and Functions, Array of structures, structure Data types, type definition, Defining,
opening and closing of files, Input and output operations, Programming examples and exercises.
Course Outcome:
Explain Structure and File I/O operations.
Definition: A structure is defined as a collection of data of same/different data types. All data items thus
grouped are logically related and can be accessed using variables. Thus, structure can also be defined as a
group of variables of same or different data types. The variables that are used to store the data are called
members of the structure or fields of the structure. In C, the structure is identified by the keyword struct.
Ex: The structure definition to hold the student information such as name, roll_number and average_marks
can be written as shown below:
Structure declaration
“How to declare a structure?” As variables are declared before they are used in the function, the structures are
also should be declared before they are used. A structure can be declared using three different ways as shown
below:
Definition:
1. The structure definition with tag name is called tagged structure. The tag name is the name of
the structure. The syntax of tagged structure is shown below:
2. Structure without a tag is where the declaration is done immediately after the definition without using
the tag name.
struct
{
type1 member1;
type2 member2;
Curly braces …… ……
…… ……
} v1, v2,…..vn ; Note: semicolon is must at the end of variables
Structure variables
3. Type-Defined Structure: The structure definition associated with keyword typedef is called
type- defined structure. This is the most powerful way of defining the
structure.
Since STUDENT is the type created by the user, it can be called as user-defined data type. From this
point onwards we can use STUDENT as data type and declare the variables. For example, consider the
following declaration:
This statement declares that the variables cse and ise are variables of type STUDENT.
Structure initialization
Assigning the values to the structure members is known as structure initialization. All the elements that
are being initialized are enclosed within the braces { and }.
Introduction to Programming With C – 19CSE13/23 Module 4
syntax:
struct tag_name variable = {v1,v2,..................vn};
Example:
struct student
{
char name[ ];
int usn;
float avg;
};
struct student std1 = {“raju” , 18, 87.5};
Example
struct student
{
char name[ ];
int usn;
float avg;
};
struct student std1 = {“raju” , 18, 87.5};
The members of structure variable std1 can be accessed using dot operator as follows:
std1.name access the string “rama”
std1.usn access the usn 18
std1.avg access the value 87.5
Write a program to read and write a structure called employee with members as name, age and salary.
#include<stdio.h>
struct employee
{
char name[ ];
int age;
float salary;
};
void main( )
{
struct employee e1;
printf(“Enter employee name\n”);
gets(e1.name);
Introduction to Programming With C – 19CSE13/23 Module 4
Array of a structure
In C language as we can have an array of integers, we can also have an array of structures.
Example: suppose you want to store the information of 10 students consisting of name and usn. The structure
definition can be written as shown below:
struct student
{
char name[ ] ;
int usn;
};
To store the information of 10 students, the structure variable has to be declared as follows:
struct student s[10];
The general syntax for structure array declaration is:
struct tag_name arrayname[size];
Write a C program to store and print name, usn, subject and IA marks of 10 students using structure
#include<stdio.h>
struct student
{
char name[20];
int usn;
char subject[20];
float marks;
};
void main()
{
struct student s[10];
int i;
for(i=0; i<10;i++)
{
printf(“Enter student name\n”);
gets(s[i].name); printf(“
Enter usn\n”); scanf(“%d”,
&s[i].usn); printf(“Enter the
subject\n”);
gets(s[i].subject);
printf(“Enter the marks\n”);
scanf(“%d”, &s[i].marks);
Introduction to Programming With C – 19CSE13/23 Module 4
}
printf(“students details are\n”);
for(i=0;i<10;i++)
{
puts(s[i].name);
printf(“%d”,s[i].usn);
puts(s[i].subject);
printf(“%d”,s[i]..marks);
}
}
the new names that are given for the already existing data types are called user defined data types. In the above
example percentage, usn and salary are user defined data types. The user defined data types can be used to
describe variables as
typedef int percentage, usn;
percentage p1, p2, p3;
usn u1,u2,u3;
The structure defined using the keyword typedef is called type defined structure.
typedef struct
{
datatype member1;
datatype member2;
---------
---------
}structure_name;
Example:
typedef struct
{
char name[20];
int usn;
}student;
Here „student‟ is the new data type using which variables can be declared as
student s1,s2;
The typedef structure can also be defined as
Example:
struct student
{
char name[20];
int usn;
Introduction to Programming With C – 19CSE13/23 Module 4
}
typedef struct student VTU
VTU s1, s2;
Nested structures
A structure can be member of another structure. This is called as a nested structure ie. A structure which
includes another structure is called a nested structure.
Example:
Consider the structure date which includes members like date, month and yesr
struct date
{
int dd;
int mm;
int yyyy;
};
The above structure date can be used in the structure employee as
struct employee
{
char name[20];
int emp_id;
float salary;
struct date doj;
};
In the above example, the date structure is nested within employee structure. in order to access the member of a
date structure, we need to first create a variable of employee structure.
struct employee e1;
Now we can access member of date structure as
e1.doj.dd;
e1.doj.mm;
e1.doj.yyyy;
Introduction to Programming With C – 19CSE13/23 Module 4
1. How structure is different from an array? Explain declaration of a structure with an example.
An array is a collection of elements of similar data types. An array behaves like a built in data type. All
we have to do is to declare an array variable and use it.
Ex: int a[10];
A structure is a collection of elements of similar or dissimilar data types. In case of a structure, first we
have to design and declare a data structure before the variables of that type are declared and used.
Ex:
struct student
{
char name[20];
int rollno;
float marks;
};
Example:
typedef struct
{
char name[20];
int usn;
}student;
Here „student‟ is the new data type using which variables can be declared as
student s1,s2;
3. Write a C program to input the following details of „N‟ students using structure: Roll No: integer,
Name: string Marks: float Grade: char. prints the names of the students with marks >-70%.
#include <stdio.h>
struct student
{
char name[50];
int roll;
int marks;
char grade[2];
};
int main()
{
struct student s[100];
int i, n, marks;
printf("Enter the number of students:\n");
scanf("%d", &n);
printf("Enter information of students:\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("\nEnter roll number \n");
scanf("%d",&s[i].roll);
printf("Enter name: ");
scanf("%s",&s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("Enter grade: ");
scanf("%s",&s[i].grade);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("Roll number: %d\n", s[i].roll);
printf("Name: %s\n", s[i].name);
printf("Marks: %d\n", s[i].marks);
printf("Grade: %s\n", s[i].grade);
printf("\n");
}
printf(“Names of students with marks greater than 75 are\n”);
for(i=0;i<n;i++)
{
if(s[i].marks >=75)
puts(s[i].name);
}
Introduction to Programming With C – 19CSE13/23 Module 4
6. Write a C program to store and print name, usn, subject and IA marks of students using
structure.
#include<stdio.h>
struct student
{
char name[20];
int usn;
char subject[20];
float marks;
};
void main()
{
struct student s[10];
int i;
for(i=0; i<10;i++)
{
printf(“Enter student name\n”);
gets(s[i].name); printf(“
Enter usn\n”); scanf(“%d”,
&s[i].usn); printf(“Enter the
subject\n”);
gets(s[i].subject);
printf(“Enter the marks\n”);
scanf(“%d”, &s[i].marks);
}
printf(“students details are\n”);
for(i=0;i<10;i++)
{
puts(s[i].name);
printf(“%d”,s[i].usn);
puts(s[i].subject);
printf(“%d”,s[i]..marks);
}
}
Introduction to Programming With C – 19CSE13/23 Module 4
8. Write a program to maintain a record of “n” student details using an array of structures with four
fields (Roll No, name, marks, and grade). Each field must be of appropriate data type. Print the
marks of the student name as input.
#include <stdio.h>
struct student
{
char name[50];
int roll;
int marks;
char grade[2];
};
int main()
{
struct student s[100];
char searchname[50];
int i, n;
printf("Enter the number of students:\n");
scanf("%d", &n);
printf("Enter information of students:\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("\nEnter roll number \n");
Introduction to Programming With C – 19CSE13/23 Module 4
scanf("%d",&s[i].roll);
printf("Enter name: ");
scanf("%s",&s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("Enter grade: ");
scanf("%s",&s[i].grade);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1); printf("Roll
number: %d\n", s[i].roll); printf("Name:
%s\n", s[i].name); printf("Marks: %d\n",
s[i].marks); printf("Grade: %s\n", s[i].grade);
printf("\n");
}
printf("Enter the Search Name of the Student :");
scanf("%s",&searchname);
for(i=0;i<n;++i)
{
if (strcmp( s[i].name, searchname ) == 0)
{
printf("%s is in the List and her marks is %d\n",s[i].name,s[i].marks);
getch();
return 0;
}
}
printf("%s Student is not in the List\n", searchname);
getch();
return 0;
}
11. Show how a structure variable is passed as a parameter to a function, with an example.
A structure variable can be passed to the function as an argument just like normal variable are passed to the
function.
Example:
Program to pass structure variable to a function.
#include<stdio.h>
struct student
Introduction to Programming With C – 19CSE13/23 Module 4
{
char name[20];
int usn;
};
void main()
{
void display( struct student s);
struct student s1;
printf(“Enter the student name\n”);
gets(s1.name);
printf(“Enter student usn\n”);
scanf(“%d\n”, &s1.usn);
displat(s1);
}
void display(struct student s)
{
puts(“name is” s.name);
printf(“usn is” s.usn);
}
Write a C program to store and print name, usn, subject and IA marks of 10 students using structure
#include<stdio.h>
struct student
{
char name[20];
int usn;
char subject[20];
float marks;
};
void main()
{
struct student s[10];
Introduction to Programming With C – 19CSE13/23 Module 4
int i;
for(i=0; i<10;i++)
{
printf(“Enter student name\n”);
gets(s[i].name); printf(“
Enter usn\n”); scanf(“%d”,
&s[i].usn); printf(“Enter the
subject\n”);
gets(s[i].subject);
printf(“Enter the marks\n”);
scanf(“%d”, &s[i].marks);
}
printf(“students details are\n”);
for(i=0;i<10;i++)
{
puts(s[i].name);
printf(“%d”,s[i].usn);
puts(s[i].subject);
printf(“%d”,s[i]..marks);
}
}
Introduction to Programming With C – 19CSE13/23 Module 4
FILE HANDLING
A file is defined as a collection of data stored on the secondary device such as hard disk. An input file
contains the same items we might have typed in from the keyboard. An output file contains the same
information that might have been sent to the screen as the output from our program.
The advantages of creating and using an input file are
It is very convenient to read input from a data file than to enter data interactively using the keyboard.
It is very difficult to input large volume of data through terminals
It is time consuming to enter large volume of data using keyboard.
When we are entering the data through the keyboard, if the program is terminated for any of
the reason or computer is turned off, the entire input data is lost.
To overcome all these problems, the concept of storing the data in disks was introduced. Here, the data can be
stored on the disks; the data can be accessed as and when required and any number of times without
destroying the data. The data is stored on the disk in the form of a file.
FILE is the derived data type defined in the header file “stdio.h”. Since, FILE is defined in “stdio.h”, we
have to include the file “stdio.h” in the beginning of the program.
Since fp is a pointer variable, it is the responsibility of the programmer to point fp to the opened file.
The program segment that shows the declaration of a file pointer is shown below:
#include <stdio.h>
void main()
{
FILE *fp; /* Here, fp is a pointer to a structure FILE */
………. /* File operations */
……….
}
Modes of a file
The various modes in which a file can be opened successfully along with meanings are shown below:
Where
fp is a file pointer of type FILE
Filename holds the name of the file to be opened.
mode can be “r” or “w” or “a”
fclose()
flose() is a function using which
An existing file can be closed. When we no longer need a file, we should close the file.
This is the last operation to be performed on a file.
This ensures that all buffers are flushed
All the links to the file are broken.
Once the file is closed, to access the file, it has to be re-opened.
If a file is closed successfully, 0 is returned otherwise EOF is returned.
The syntax is shown below:
fclose(fp);
When the function fopen() is executed and if the file does not exist, the function fopen() returns NULL. In this
situation, we display the message “Error in opening the file” as shown below:
if (fp == NULL) // If the file does not exist
{
printf(“Error in opening the file”);
exit(0);
}
If the file is existing, the function fopen() returns a pointer to the file which points to the beginning of the file
and it is copied into file pointer variable fp as shown in figure below:
input.txt
NEW HORIZON COLLEGE OF ENGINEERINGΔ
EOF
fp
The final program segment to open an existing/non-existing file can be written as shown below:
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “r”); // Open the file
if (fp == NULL) // If file does not exist
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}
/* Read the opened file and perform various operations
………..
fclose(fp); // close the file
Case 1: Read only file exists: Suppose the read only file “input.txt” is opened for writing. Since the file is read
only, it should not be modified. So, the function fopen() returns NULL. It indicates that it is an error and the file
should not be opened. The code for this can be written as shown below:
if (fp == NULL)
{
Introduction to Programming With C – 19CSE13/23 Module 4
EOF
Now, once fopen() is executed, the contents of the file are erased and file pointer points to the beginning of the
file as shown below:
input.txt
fp
Now, we can start writing into the file from fp onwards as if it is a new file. Suppose, a string “Subject videos
:www.gat.ac.in” is written into the file. The contents of the file are shown below:
input.txt
Welcome to C Programming Δ
EOF
So, when a normal file is opened in write mode, the contents of the given file are deleted. The file pointer points
to the beginning of the file and we can start writing the characters into the file. Now, the file pointer will always
points to the end of the file.
Case 3: File does not exist: Suppose, the file “input.txt” is opened for writing and the file does not exist. Now, a
new file “input.txt” is created and the function fopen() returns a pointer to the beginning of the file and it is stored
in the variable fp as shown below:
input.txt
fp
Now, we can start writing into the file from fp onwards. Suppose we write the string “Global Academy
of
Technology”, then the contents of the file is shown below:
Introduction to Programming With C – 19CSE13/23 Module 4
fp
input.txt
NEW HORIZON COLLEGE OF ENGINEERINGΔ
EOF
So, when a non-existing file is opened in write mode, a new file is created and we can write into the file. Now, the
file pointer will always points to the end of the file. The final program segment can be written as shown below:
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “w”); // Create the file
if (fp == NULL) // If file cannot be created
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}
// write the data into the file
………..
fclose(fp); // close the file
Case 1: Read only file exists: Since the file is read only, it should not be modified. So, the function fopen() returns
NULL. It indicates that it is an error and the file should not be opened. The code for this can be written as shown
below:
if (fp == NULL)
{
printf(“Error in opening the file”);
exit(0);
}
So, when a read only file is opened in append mode, we cannot perform any operations on the file and hence
after displaying the message “Error in opening the file” the program is terminated.
Case 2: Normal file exists: Suppose, the file “input.txt” exists as shown below:
Introduction to Programming With C – 19CSE13/23 Module 4
input.txt
NEW HORIZON COLL
EOF
Now, once fopen() is executed, the file pointer points to the end of the file as shown below:
input.txt
NEW HORIZON COLL
fp
Now, we can start appending into the file from fp onwards as if it is a new file. The file after
appending a
sequence of characters “of Technology” is shown below:
fp
input.txt
NEW HORIZON COLLEGE OF ENGINEERINGΔ
EOF
So, when a normal file is opened in append mode, we can insert the characters at the end of the file. Now, the file
pointer will always points to the end of the file.
Case 3: File does not exist: Suppose, the file “input.txt” has to be opened for appending and the file does not
exist. Now, a new file “input.txt” is created and the function fopen() returns a pointer to the beginning of the file
and it is stored in the variable fp as shown below:
input.txt
fp
Now, we can start appending into the file from fp onwards. When the string “Global Academy of Technology”
is written into the file, the contents of the file are shown below:
So, when a non-existing file is opened in append mode, a new file is created and we can write into the file. Now,
the file pointer will always points to the end of the file as shown in above figure. The final program
segment can be written as shown below:
Introduction to Programming With C – 19CSE13/23 Module 4
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “a”); // Open the file
if (fp == NULL) // If file cannot be appended
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}
// append the data into the file
………..
fclose(fp); // close the file
fscanf: The function of fscanf and scanf are exactly same. Only change is that scanf is used to get data input from
keyboard, whereas fscanf is used to get data from the file pointed to by fp. Because input is read from the file,
extra parameter file pointer fp has to be passed as the parameter. Rest of the functionality of fscanf remains same
as scanf. The syntax of fscanf() is shown below:
fscanf(fp, “format string”, list);
where
fp is a file pointer. It can point to a source file or standard input stdin. If fp is pointing to stdin, data is
read from the keyword. If fp points to source file, the data is read from the specified source file.
format string and list have the same meaning as in scanf() i.e., the variables specified in the list will
take the values from the file specified by fp using the specifications provided in format string.
The function returns EOF when it attempts to read at the end of the file; Otherwise, it returns
the number of items read in and successfully converted
Example:
fscanf(fp, “%d %s %f”, &id, name, &avg_marks);
Suppose, fp points to the source file. After executing above statement, the values for the variables id, name and
avg_marks are obtained from the file associated with file pointer fp. This function returns the number of items
that are successfully read from the file.
fprintf: The function of fprintf and printf are exactly same. Only change is that printf is used to display the data
onto the video display unit, whereas fprintf is used to send the data to the output file pointed to by fp. Since file
is used, extra parameter file pointer fp has to be passed as parameter. Rest of the functionality of fprintf
remains same as printf. The syntax of fprintf() is shown below:
fprintf(fp, “format string”, list);
where
fp is a file pointer associated with a file that has been opened for writing.
Introduction to Programming With C – 19CSE13/23 Module 4
format string and list have the same meaning as in printf() function i.e., the values of the variables
specified in the list will be written into the file associated with file pointer fp using the specifications
provided in format string.
Example:
fprintf(fp, “%d %s %f”, id, name, avg_marks);
After executing fprintf, the values of the variables id, name and avg_marks are written into the file associated
with file pointer fp. This function returns the number of items that are successfully written into the file.
#include <stdio.h>
void main()
{
FILE *fp;
int num;
fp = fopen(“input.dat”, “w”); // Open the file in write mode
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
while (scanf(“%d”, &num) != EOF) // 10 20 30 40 50 Cntl-z (Turbo)
{ // Cntl-d (linux)
fprintf(fp,“%d\n”, num); // The above data is written into
} // file : input.dat
fclose(fp);
}
C program to read n numbers from input file and display on the screen
#include <stdio.h>
void main()
{
FILE *fp;
int num;
fp = fopen(“input.dat”, “r”); // input.dat : 10 20 30 40 50
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
while (fscanf(fp, “%d”, &num) > 0)
{ // Output
printf(“%d\n”, num); // 10 20 30 40 50
}
fclose(fp);
Introduction to Programming With C – 19CSE13/23 Module 4
C program to read student name and usn from two different files and write into a different file in the
sequence
#include <stdio.h>
void main()
{
FILE *fp1, *fp2, *fp3;
char name[20];
int usn;
fp1 = fopen(“studentname.txt”, “r”); // Open the name file in read mode
fp2 = fopen(“usn.txt”, “r”); // Open the usn file in read mode
fp3 = fopen(“output.txt”, “w”); // Open the file in write mode
for(;;)
{
if ( fscanf(fp1, “%s”, name) > 0) // read name from 1st file
{
if (fscanf(fp2, “%d”, &usn) > 0) // read name from 2nd file
{
fprintf(fp3,”%s %d\n”, name, usn); // write to 3rd file
}
else break;
}
else break;
}
fclose(fp1); /* close all the files */
fclose(fp2);
fclose(fp3);
}
Introduction to Programming With C – 19CSE13/23 Module 4
Where
fp is a file pointer of type FILE
Filename holds the name of the file to be opened.
mode can be “r” or “w” or “a”
fclose()
flose() is a function using which
An existing file can be closed. When we no longer need a file, we should close the file.
This is the last operation to be performed on a file.
This ensures that all buffers are flushed
All the links to the file are broken.
Once the file is closed, to access the file, it has to be re-opened.
Introduction to Programming With C – 19CSE13/23 Module 4
fscanf()
The function of fscanf and scanf are exactly same. Only change is that scanf is used to get data input from
keyboard, whereas fscanf is used to get data from the file pointed to by fp. Because input is read from the file,
extra parameter file pointer fp has to be passed as the parameter. Rest of the functionality of fscanf remains same
as scanf. The syntax of fscanf() is shown below:
fscanf(fp, “format string”, list);
where
fp is a file pointer. It can point to a source file or standard input stdin. If fp is pointing to stdin, data is
read from the keyword. If fp points to source file, the data is read from the specified source file.
format string and list have the same meaning as in scanf() i.e., the variables specified in the list will
take the values from the file specified by fp using the specifications provided in format string.
The function returns EOF when it attempts to read at the end of the file; Otherwise, it returns
the number of items read in and successfully converted
Example:
fscanf(fp, “%d %s %f”, &id, name, &avg_marks);
Suppose, fp points to the source file. After executing above statement, the values for the variables id, name and
avg_marks are obtained from the file associated with file pointer fp. This function returns the number of items
that are successfully read from the file.
fprintf()
The function of fprintf and printf are exactly same. Only change is that printf is used to display the data onto the
video display unit, whereas fprintf is used to send the data to the output file pointed to by fp. Since file is used,
extra parameter file pointer fp has to be passed as parameter. Rest of the functionality of fprintf remains same as
printf. The syntax of fprintf() is shown below:
fprintf(fp, “format string”, list);
where
fp is a file pointer associated with a file that has been opened for writing.
format string and list have the same meaning as in printf() function i.e., the values of the variables
specified in the list will be written into the file associated with file pointer fp using the specifications
provided in format string.
Example:
fprintf(fp, “%d %s %f”, id, name, avg_marks);
After executing fprintf, the values of the variables id, name and avg_marks are written into the file associated
with file pointer fp. This function returns the number of items that are successfully written into the file.
fgets()
The syntax of fgets() is shown below
ps = fgets(str, n, fp);
where
fp is a file pointer. It can point to a source file or standard input.
str is an array of characters
Introduction to Programming With C – 19CSE13/23 Module 4
2. Write a C program to read the contents from the file called abc.txt, count the number of
characters, number of lines and number of words and output the same.
#include <stdio.h>
int main()
{
FILE *fp;
char filename[100];
char ch;
int linecount= 0, wordcount=0, charcount=0;
fp = fopen(“abc.txt”,"r");
if ( fp )
{
while ((ch=getc(fp)) != EOF)
{
if (ch != ' ' && ch != '\n')
{
++charcount;
}
if (ch == ' ' || ch == '\n')
{
++wordcount;
}
if (ch == '\n')
{
++linecount;
}
}
if (charcount > 0)
{
++linecount;
++wordcount;
}
}
else
{
getchar();
return(0);
}
Example:
#include <stdio.h>
int main ()
{
FILE *fp;
int ch;
fp = fopen("file.txt", "w+");
for( ch = 33 ; ch <= 100; ch++ )
{
fputc(ch, fp);
}
fclose(fp);
return(0);
}
fputs()
The C library function int fputs(const char *str, FILE *fp) writes a string to the specified stream up to but not
including the null character.
Syntax:
int fputs(const char *str, FILE *stream)
str -- This is an array containing the null-terminated sequence of characters to be written.
fp-- This is the pointer to a FILE object that identifies the stream where the string is to be written.
Example:
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is c programming.", fp);
fputs("This is a system programming language.", fp);
fclose(fp);
return(0);
}
Introduction to Programming With C – 19CSE13/23 Module 4
fgetc()
The C library function int fgetc(FILE *fp) gets the next character (an unsigned char) from the specified stream
and advances the position indicator for the stream.
Syntax:
int fgetc(FILE *fp)
fp -- This is the pointer to a FILE object that identifies the stream on which the operation is
to be performed.
Example:
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
int n = 0;
fp = fopen("file.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
}
do
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}while(1);
fclose(fp);
return(0);
}
fgets()
The C library function char *fgets(char *str, int n, FILE *fp) reads a line from the specified stream and stores
it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or
the end-of-file is reached, whichever comes first.
Syntax:
char *fgets(char *str, int n, FILE *fp)
tr -- This is the pointer to an array of chars where the string read is stored.
n -- This is the maximum number of characters to be read (including the final null-character). Usually,
the length of the array passed as str is used.
fp -- This is the pointer to a FILE object that identifies the stream where characters are read from.
Introduction to Programming With C – 19CSE13/23 Module 4
Example:
#include <stdio.h>
int main()
{
FILE *fp;
char str[60];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
if( fgets (str, 60, fp)!=NULL )
{
/* writing content to stdout */
puts(str);
}
fclose(fp);
return(0);
}
Where
fp is a file pointer of type FILE
Filename holds the name of the file to be opened.
mode can be “r” or “w” or “a”
Introduction to Programming With C – 19CSE13/23 Module 4
fclose()
flose() is a function using which
An existing file can be closed. When we no longer need a file, we should close the file.
This is the last operation to be performed on a file.
This ensures that all buffers are flushed
All the links to the file are broken.
Once the file is closed, to access the file, it has to be re-opened.
If a file is closed successfully, 0 is returned otherwise EOF is returned.
The syntax is shown below:
fclose(fp);