EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

File Handling in C

Home » Software Development » Software Development Tutorials » C Programming Tutorial » File Handling in C

File Handling in C

Introduction to File Handling in C

File handling in C is a process where some bytes of data can be written and stored permanently in the disk so that in a later point of time, the relatable data can be fetched and referred. File Handling in C makes use of structure pointer of the file type to declare a file. For Example, An application is developed, and it is very much needed to store some important file settings then it is mandatory to support file handling to store that data of the settings permanently for later reference and manipulation.

File Handling Functions in C

Most often programs are executed on terminals but in industries, the application runs should have some proof or records to be referred at some point in time. Therefore, it is very much needed to store these applications executed data somewhere and then file handling is used. It is used to write those data somewhere and save it permanently. Some pointer related structures are used to point towards that sort of file for reference. Different File handling Functions in C are as follows:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • fopen [with an extra attribute such as ‘a’ or ‘b’]: For creating a new file.
  • fopen: Opening of an existing file.
  • fscanf or fgetc: Reading from a file.
  • fprintf or fputs: Writing to file.
  • rewind, fseek: Moving to a certain or specific location within a file.
  • fclose: Closing of a file.

Attributes to File Handling

For creating a new file using different attributes of file handling:

 There are certain privileges which are needed to be provided to the file while opening or we can say kind of access control. As mentioned earlier certain specific types of pointer structures are needed for file to point these attributes are part of that only.  These attributes are as follows:

  • “r”: It is used to search a file and then once the search gets complete and the file is opened, fopen will load it into memory and will set up a pointer that will point to the first character of the file. In case the file is not able to open then it will return a NULL value.
  • “w”: It will first search for a file and once a file gets searched successfully and it exists then all the contents get overwritten. In case the file is not existing, it will create a new file and returns null if the file is not able to open.
  • “a”: It also works in similar fashion as that of r, but the only difference Is that the pointer will point to the last character of the file. In case the file is not able to get opened it will again return a NULL value.
  • “r+”: It is also an attribute that works the same as r just naming Is different, attribute points to the first character only.
  • “w+”: It also works the same as ‘w’ just the difference lies in the naming convention.
  • “a+”: It also works the same as ‘a’ just the difference lies in the naming convention.

Syntax:

FILE *filePointer;

So, the file can be opened as

filePointer = fopen (“file.txt”, “a”)

Note: Parameters can be changed according to the above-mentioned list of attributes.

Some main functions with its syntaxes to perform some common operations are as follows:

  • Reading from a file.
  • Writing a file.
  • Closing a file.

1. Reading from a file

Reading from a file involves the usage of both fscanf and fgets. Both functions are almost similar to the fact that both have the same functionality with a difference of using an additional parameter, the file pointer which can be used either to read a file line by line or character by character.

 Syntax:

FILE * filePointer;
filePointer = fopen (“file.txt”, “r”);
fscanf (filePointer, "%s %s %s %d", str1, str2, str3, &date);

Popular Course in this category
C Programming Training (3 Courses, 5 Project)3 Online Courses | 5 Hands-on Projects | 34+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,617 ratings)
Course Price

View Course

Related Courses
C++ Training (4 Courses, 5 Projects, 4 Quizzes)Java Training (40 Courses, 29 Projects, 4 Quizzes)

2. Writing a file

Writing in a file can be done using both the functions fprintf and fputs in the same way as read operations.

Syntax:

FILE *filePointer;
filePointer = fopen (“file.txt”, “w”);
fprintf (filePointer, "%s %s %s %d", "we", "live", "in",2020);

3. Closing a file

Once all operations are performed successfully and it is always asked to close the file and for closing any file it is very much needed to use fclose function.

 Syntax:

FILE *filePointer;
filePointer= fopen (“file.txt”, “w”);
# Perform some file operations and then close it
fclose(filePointer)

Examples to Implement File Handling in C

Below are the examples to implement in File Handling in C:

Example #1

Program for opening a file, writing and closing a file.

Code:

#include <stdio.h>
#include <string.h>
int main ()
{
FILE *filePointer;
char dataToWrite [50] = "Educba - portal for learning";
filePointer = fopen ("file_handling_test.c", "w");
if (filePointer == NULL)
{
printf ("file_handling_test.c file fails to get open.");
}
else
{
printf ("The file gets opened.\n");
if (strlen (dataToWrite) > 0)
{
fputs (dataToWrite, filePointer);
fputs ("\n", filePointer);
}
fclose(filePointer);
printf ("Data gets successfully written in file file_handling_test.c\n");
printf ("File now gets closed.");
}
return 0;
}

Output: For the main file, the output is as.

File Handling in C - 1

Output: For file_handling_test is as.

File Handling in C - 2

Example #2

Program to Open a file, Read from it and close that file.

Code:

#include <stdio.h>
#include <string.h>
int main ()
{
FILE *filePointer;
char dataToRead [50];
filePointer = fopen ("File_Read_Test.c", "r");
if (filePointer == NULL)
{
printf ("File_Read_Test.c file gets failed to open.");
}
else
{
printf ("The file then gets opened.\n");
while(fgets (dataToRead, 50, filePointer) != NULL)
{
printf ("%s", dataToRead);
}
fclose(filePointer);
printf ("Data successfully gets read from the file File_Read_Test.c\n");
printf ("The file then gets closed.");
}
return 0;
}

Output:

File Handling in C - 3

Note: A common structure is followed syntactically in terms of the file handling operations like opening a file, writing a file, reading a file and then closing a file with a mere difference of functions to be used with attributes in all scenarios.

Conclusion

File Handling in any programming language not only in C plays a very important role especially in the industry as it will store the data in memory permanently which can be referred later at any point in time. This is a special characteristic of the file handling feature.

Recommended Articles

This is a guide to File Handling in C. Here we discuss function in fil handling, different attributes with examples to implement with appropriate syntax as well. You can also go through our other related articles to learn more –

  1. C Literals
  2. File Handling in C++
  3. File Handling in JavaScript
  4. Java File Class

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C Programming Tutorial
  • Advanced
    • Constructor in C
    • Encapsulation in C
    • C Storage Classes
    • Static Keyword in C
    • File Handling in C
    • Queue in C
    • Hexadecimal in C 
    • typedef in C
    • Memory Allocation in C
    • Linked List in C
    • Volatile in C
    • Tokens in C
    • Expression in C
    • Regular Expression in C
    • Error Handling in C
    • Types of Errors in C
    • Preprocessor in C
    • Preprocessor Directives in C
    • fscanf() in C
    • #Pragma in C
    • #ifndef in C
    • #undef in C
    • Macros in C
  • Basic
    • Introduction to C
    • What is C
    • Career in C Programming
    • Advantages of C
    • How to Install C
    • Best C Compilers
    • Data Types in C
    • Variables in C
    • C Keywords
    • C Command
    • Command Line Arguments in C
    • C Literals
    • Constants in C
    • Unsigned Int in C
    • String in C
  • Pointers
    • Pointers in C
    • Null pointer in C
    • Function Pointer in C
    • Double Pointer in C
    • Void Pointer in C
    • Const Pointer in C
    • Dangling Pointers in C
    • Pointer Arithmetic in C
  • Operators
    • C Operators
    • Arithmetic Operators in C
    • Relational Operators in C
    • Assignment Operators in C
    • Logical Operators in C
    • Conditional Operator in C
    • Modulus Operator in C
    • Ternary Operator in C
    • Address Operator in C
    • Unary Operator in C
    • Operators Precedence in C
    • Left Shift Operator in C
  • Control Statement
    • Control Statements in C
    • If Statement in C
    • If-else Statement in C
    • Else if Statement in C
    • Nested if Statement in C
    • #else in C
    • Structure Padding in C
    • Nested Structure in C
    • Continue Statement in C
    • Break Statement in C
    • Switch Statement in C
    • Goto Statement in C
  • Loops
    • Loops in C
    • For Loop in C
    • While Loop in C
    • Do While Loop in C
    • Nested Loop in C
    • Infinite Loop in C 
  • Function
    • Math Functions in C
    • Hashing Function in C
    • Recursive Function in C
    • Power Function in C
    • fputs in C
    • C puts() Function
    • fprintf() in C
    • fseek() in C
    • Stderr in C
    • ASCII Value in C
    • strcat() in C
    • Inline Function in C
    • sizeof() in C
    • Function Prototype in C
    • C ftell()
  • Array
    • Arrays in C Programming
    • 2-D Arrays in C
    • 3D Arrays in C
    • Multidimensional Array in C
    • Array Functions in C
    • Strings Array in C
  • Sorting
    • Sorting in C
    • Heap Sort in C
  • C programs
    • Patterns in C Programming
    • Star Patterns in C
    • Number Patterns in C
    • Swapping in C
    • Reverse Number in C
    • Palindrome in C Program
    • Factorial in C
    • Fibonacci Series in C
    • Square Root in C
    • Random Number Generator in C
    • Prime Numbers in C
    • Escape Sequence in C
    • Reverse String in C
    • Leap Year Program in C
    • Anagram Program in C
    • Strong Number in C
    • String Concatenation in C
    • C Programming Matrix Multiplication
    • Decimal to Octal in C
    • Expression Evaluation in C
    • Decimal to Hexadecimal in C
  • Interview question
    • C Programming Interview Questions

Related Courses

C Programming Training Course

C++ Training Course

Java Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C Programming Training Course Learn More