SlideShare a Scribd company logo
1 of 23
Introduction to Data Structures
Affiliated KSWU, Vijayapura
Subscribe to my channel: http://www.youtube.com/c/SPSajjan
Facebook Page : https://www.facebook.com/sajjanvsl
website: http://sajjanvsl.blogspot.com
Pointer to a Structure in C
We have already learned that a pointer is a
variable which points to the address of another
variable of any data type like int, char, float etc.
Similarly, we can have a pointer to structures, where a
pointer variable can point to the address of a structure
variable. Here is how we can declare a pointer to a
structure variable.
Pointer to array of string
struct dog
{
char name[10];
char breed[10];
int age; char color[10];
}; struct dog spike; // declaring a pointer to a structure of type struct
dog struct dog *ptr_dog
1 : Printing Address of the Character Array
Here's how you can create pointers to structs.
struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr, Harry;
}
Here, ptr is a pointer to struct.
Accessing members using Pointer
There are two ways of accessing members of structure using pointer:
Using indirection (*) operator and dot (.) operator.
Using arrow (->) operator or membership operator.
Let's start with the first one.
Using Indirection (*) Operator and Dot (.) Operator
At this point ptr_dog points to the structure variable spike, so by dereferencing
it we will get the contents of the spike. This means spike and *ptr_dog are
functionally equivalent. To access a member of structure
write *ptr_dog followed by a dot(.) operator, followed by the name of the
member. For example:
(*ptr_dog).name - refers to the name of dog
(*ptr_dog).breed - refers to the breed of dog
and so on.
Parentheses around *ptr_dog are necessary because the precedence of dot(.)
operator is greater than that of indirection (*) operator.
Using arrow operator (->)
The above method of accessing members of the structure using pointers is slightly
confusing and less readable, that's why C provides another way to access
members using the arrow (->) operator. To access members using arrow (->)
operator write pointer variable followed by -> operator, followed by name of the
member.
1 2
ptr_dog->name // refers to the name of dog ptr_dog->breed // refers to the breed
of dog
and so on.
Here we don't need parentheses, asterisk (*) and dot (.) operator. This method is
much more readable and intuitive.
C - Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer
to a pointer, the first pointer contains the address of the second pointer, which
points to the location that contains the actual value as shown below.
Pointer to Pointer in C
A variable that is a pointer to a pointer must be declared as such. This is done by
placing an additional asterisk in front of its name. For example, the following
declaration declares a pointer to a pointer of type int −
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing
that value requires that the asterisk operator be applied twice, as is shown
below in the example −
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %dn", var );
printf("Value available at *ptr = %dn", *ptr );
printf("Value available at **pptr = %dn", **pptr);
return 0;
}
When the above code is compiled and executed, it produces the following result
−
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
File Management in C: Defining and Opening &
Closing File,
Declaring, Opening & Closing File Streams in C Programming
This lesson explains handling file operations, like opening
and closing a file, in C programming. You will also learn how
to perform read and write operations on a file. Various
examples are shown to understand file streams.
Handling File Streams in C
A file can be treated as external storage. It consists of a sequence of
bytes residing on the disk. Groups of related data can be stored in a
single file. A program can create, read, and write to a file. Unlike an
array, the data in the file is retained even after the program finishes its
execution. It's a permanent storage medium.
Declaring a File Pointer
In C language, in order to declare a file, we use a file pointer. A
file pointer is a pointer variable that specifies the next byte to
be read or written to. Every time a file is opened, the file pointer
points to the beginning of the file. A file is declared as follows:
FILE *fp;
//fp is the name of the file pointer
Opening, Creating, Closing
C language provides a number of functions to perform file
handling. fopen() is used to create a new file or open an existing
file. The syntax is as follows:
fp = FILE *fopen(const char *filename, const char *mode);
fp is the file pointer that holds the reference to the file,
the filename is the name of the file to be opened or created,
and mode specifies the purpose of opening a file such as for
reading or writing. FILE is an object type used for storing
information about the file stream.
A file can be opened in different modes. Below are some of the
most commonly used modes for opening or creating a file.
r : opens a text file in reading mode.
w : opens or creates a text file in writing mode.
a : opens a text file in append mode.
r+ : opens a text file in both reading and writing mode. The file must exist.
w+ : opens a text file in both reading and writing mode. If the file exists, it's
truncated first before overwriting. Any old data will be lost. If the file doesn't exist,
a new file will be created.
a+ : opens a text file in both reading and appending mode. New data is appended
at the end of the file and does not overwrite the existing content.
rb : opens a binary file in reading mode.
wb : opens or creates a binary file in writing mode.
ab : opens a binary file in append mode.
rb+ : opens a binary file in both reading and writing mode, and the original
content is overwritten if the file exists.
wb+: opens a binary file in both reading and writing mode and works similar to the
w+ mode for binary files. The file content is deleted first and then
new content is added.
ab+: opens a binary file in both reading and appending mode and
appends data at the end of the file without overwriting the existing
content.
A file needs to be closed after a read or write operation to release
the memory allocated by the program. In C, a file is closed using
the fclose() function. This returns 0 on success and EOF in the case
of a failure. An EOF is defined in the library called stdio.h. EOF is a
constant defined as a negative integer value which denotes that the
end of the file has reached.
fclose( FILE *fp );
Writing and Reading
Now that you've learned how to create a file in various modes and also how to
close a file, you must be wondering: how would you perform input and output
operations in a file? The fputc() and fputs() functions are used to write
characters and strings respectively in a file. Let's see how it's used.
int fputc( int c, FILE *fp );
This function writes a character c into the file with the help of the file pointer fp.
It returns EOF in the case of an error.
int fputs( const char *s, FILE *fp );
This function writes string s to the file with the help of the reference pointer fp.
The fgetc(), fgets(), and fscanf() are functions used in C programming language
to read characters or strings from a file. Let's discuss these, one by one.
How to Create a File
1. Whenever you want to work with a file, the first step is to create a
file. A file is nothing but space in a memory where data is stored.
2. To create a file in a 'C' program following syntax is used,
3. FILE *fp; fp = fopen ("file_name", "mode");
4. In the above syntax, the file is a data structure which is defined in
the standard library.
5. fopen is a standard function which is used to open a file.
6. If the file is not present on the system, then it is created and then
opened.
7. If a file is already present on the system, then it is directly opened
using this function.
8. fp is a file pointer which points to the type file.
Example:
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.txt", "w");
}
Output:
File is created in the same folder where you have saved your code.
How to Close a fileExample:
FILE *fp; fp = fopen ("data.txt", "r"); fclose (fp);
The fclose function takes a file pointer as an argument. The file
associated with the file pointer is then closed with the help of
fclose function. It returns 0 if close was successful and EOF (end of
file) if there is an error has occurred while file closing.
After closing the file, the same file pointer can also be used with
other files.
In 'C' programming, files are automatically close when the program
is terminated. Closing a file manually by writing fclose function is a
good programming practice
Writing to a File
1.In C, when you write to a file, newline characters 'n' must be
explicitly added.
2.The stdio library offers the necessary functions to write to a file:
3.fputc(char, file_pointer): It writes a character to the file pointed
to by file_pointer.
4.fputs(str, file_pointer): It writes a string to the file pointed to by
file_pointer.
5.fprintf(file_pointer, str, variable_lists): It prints a string to the file
pointed to by file_pointer. The string can optionally include
format specifiers and a list of variables variable_lists.
https://www.youtube.com/channel/U
CbCohw2YjjHFm-fo2qbLulg
https://www.facebook.com/sajjanvsl
CLICK HERE to
subscribe to the channel

More Related Content

What's hot

Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Hassan Ahmed
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
Kumar
 

What's hot (20)

Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introduction
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Data Structure Basics
Data Structure BasicsData Structure Basics
Data Structure Basics
 
Data structures
Data structuresData structures
Data structures
 
Data Structure
Data StructureData Structure
Data Structure
 
Data structures
Data structuresData structures
Data structures
 
Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
 
Data Structures
Data StructuresData Structures
Data Structures
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
 
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Datastructure
DatastructureDatastructure
Datastructure
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer Science
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
 
Data Structures (BE)
Data Structures (BE)Data Structures (BE)
Data Structures (BE)
 
Introduction To Data Structures.
Introduction To Data Structures.Introduction To Data Structures.
Introduction To Data Structures.
 

Similar to Introduction to Data Structure : Pointer

Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
Muhammed Thanveer M
 

Similar to Introduction to Data Structure : Pointer (20)

Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
 
5 Structure & File.pptx
5 Structure & File.pptx5 Structure & File.pptx
5 Structure & File.pptx
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Handout#01
Handout#01Handout#01
Handout#01
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
Satz1
Satz1Satz1
Satz1
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File management
File managementFile management
File management
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Programming in C
Programming in CProgramming in C
Programming in C
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

Introduction to Data Structure : Pointer

  • 1. Introduction to Data Structures Affiliated KSWU, Vijayapura Subscribe to my channel: http://www.youtube.com/c/SPSajjan Facebook Page : https://www.facebook.com/sajjanvsl website: http://sajjanvsl.blogspot.com
  • 2. Pointer to a Structure in C We have already learned that a pointer is a variable which points to the address of another variable of any data type like int, char, float etc. Similarly, we can have a pointer to structures, where a pointer variable can point to the address of a structure variable. Here is how we can declare a pointer to a structure variable.
  • 3. Pointer to array of string struct dog { char name[10]; char breed[10]; int age; char color[10]; }; struct dog spike; // declaring a pointer to a structure of type struct dog struct dog *ptr_dog
  • 4. 1 : Printing Address of the Character Array Here's how you can create pointers to structs. struct name { member1; member2; . . }; int main() { struct name *ptr, Harry; } Here, ptr is a pointer to struct.
  • 5. Accessing members using Pointer There are two ways of accessing members of structure using pointer: Using indirection (*) operator and dot (.) operator. Using arrow (->) operator or membership operator. Let's start with the first one.
  • 6. Using Indirection (*) Operator and Dot (.) Operator At this point ptr_dog points to the structure variable spike, so by dereferencing it we will get the contents of the spike. This means spike and *ptr_dog are functionally equivalent. To access a member of structure write *ptr_dog followed by a dot(.) operator, followed by the name of the member. For example: (*ptr_dog).name - refers to the name of dog (*ptr_dog).breed - refers to the breed of dog and so on. Parentheses around *ptr_dog are necessary because the precedence of dot(.) operator is greater than that of indirection (*) operator.
  • 7. Using arrow operator (->) The above method of accessing members of the structure using pointers is slightly confusing and less readable, that's why C provides another way to access members using the arrow (->) operator. To access members using arrow (->) operator write pointer variable followed by -> operator, followed by name of the member. 1 2 ptr_dog->name // refers to the name of dog ptr_dog->breed // refers to the breed of dog and so on. Here we don't need parentheses, asterisk (*) and dot (.) operator. This method is much more readable and intuitive.
  • 8. C - Pointer to Pointer A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. Pointer to Pointer in C A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type int − int **var;
  • 9. When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example − #include <stdio.h> int main () { int var; int *ptr; int **pptr; var = 3000; /* take the address of var */ ptr = &var; /* take the address of ptr using address of operator & */ pptr = &ptr;
  • 10. /* take the value using pptr */ printf("Value of var = %dn", var ); printf("Value available at *ptr = %dn", *ptr ); printf("Value available at **pptr = %dn", **pptr); return 0; } When the above code is compiled and executed, it produces the following result − Value of var = 3000 Value available at *ptr = 3000 Value available at **pptr = 3000
  • 11. File Management in C: Defining and Opening & Closing File,
  • 12. Declaring, Opening & Closing File Streams in C Programming This lesson explains handling file operations, like opening and closing a file, in C programming. You will also learn how to perform read and write operations on a file. Various examples are shown to understand file streams. Handling File Streams in C A file can be treated as external storage. It consists of a sequence of bytes residing on the disk. Groups of related data can be stored in a single file. A program can create, read, and write to a file. Unlike an array, the data in the file is retained even after the program finishes its execution. It's a permanent storage medium.
  • 13. Declaring a File Pointer In C language, in order to declare a file, we use a file pointer. A file pointer is a pointer variable that specifies the next byte to be read or written to. Every time a file is opened, the file pointer points to the beginning of the file. A file is declared as follows: FILE *fp; //fp is the name of the file pointer
  • 14. Opening, Creating, Closing C language provides a number of functions to perform file handling. fopen() is used to create a new file or open an existing file. The syntax is as follows: fp = FILE *fopen(const char *filename, const char *mode); fp is the file pointer that holds the reference to the file, the filename is the name of the file to be opened or created, and mode specifies the purpose of opening a file such as for reading or writing. FILE is an object type used for storing information about the file stream. A file can be opened in different modes. Below are some of the most commonly used modes for opening or creating a file.
  • 15. r : opens a text file in reading mode. w : opens or creates a text file in writing mode. a : opens a text file in append mode. r+ : opens a text file in both reading and writing mode. The file must exist. w+ : opens a text file in both reading and writing mode. If the file exists, it's truncated first before overwriting. Any old data will be lost. If the file doesn't exist, a new file will be created. a+ : opens a text file in both reading and appending mode. New data is appended at the end of the file and does not overwrite the existing content. rb : opens a binary file in reading mode. wb : opens or creates a binary file in writing mode. ab : opens a binary file in append mode. rb+ : opens a binary file in both reading and writing mode, and the original content is overwritten if the file exists. wb+: opens a binary file in both reading and writing mode and works similar to the
  • 16. w+ mode for binary files. The file content is deleted first and then new content is added. ab+: opens a binary file in both reading and appending mode and appends data at the end of the file without overwriting the existing content. A file needs to be closed after a read or write operation to release the memory allocated by the program. In C, a file is closed using the fclose() function. This returns 0 on success and EOF in the case of a failure. An EOF is defined in the library called stdio.h. EOF is a constant defined as a negative integer value which denotes that the end of the file has reached. fclose( FILE *fp );
  • 17. Writing and Reading Now that you've learned how to create a file in various modes and also how to close a file, you must be wondering: how would you perform input and output operations in a file? The fputc() and fputs() functions are used to write characters and strings respectively in a file. Let's see how it's used. int fputc( int c, FILE *fp ); This function writes a character c into the file with the help of the file pointer fp. It returns EOF in the case of an error. int fputs( const char *s, FILE *fp ); This function writes string s to the file with the help of the reference pointer fp. The fgetc(), fgets(), and fscanf() are functions used in C programming language to read characters or strings from a file. Let's discuss these, one by one.
  • 18. How to Create a File 1. Whenever you want to work with a file, the first step is to create a file. A file is nothing but space in a memory where data is stored. 2. To create a file in a 'C' program following syntax is used, 3. FILE *fp; fp = fopen ("file_name", "mode"); 4. In the above syntax, the file is a data structure which is defined in the standard library. 5. fopen is a standard function which is used to open a file. 6. If the file is not present on the system, then it is created and then opened. 7. If a file is already present on the system, then it is directly opened using this function. 8. fp is a file pointer which points to the type file.
  • 19. Example: #include <stdio.h> int main() { FILE *fp; fp = fopen ("data.txt", "w"); } Output: File is created in the same folder where you have saved your code.
  • 20. How to Close a fileExample: FILE *fp; fp = fopen ("data.txt", "r"); fclose (fp); The fclose function takes a file pointer as an argument. The file associated with the file pointer is then closed with the help of fclose function. It returns 0 if close was successful and EOF (end of file) if there is an error has occurred while file closing. After closing the file, the same file pointer can also be used with other files. In 'C' programming, files are automatically close when the program is terminated. Closing a file manually by writing fclose function is a good programming practice
  • 21. Writing to a File 1.In C, when you write to a file, newline characters 'n' must be explicitly added. 2.The stdio library offers the necessary functions to write to a file: 3.fputc(char, file_pointer): It writes a character to the file pointed to by file_pointer. 4.fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer. 5.fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by file_pointer. The string can optionally include format specifiers and a list of variables variable_lists.
  • 22.