{"id":3541,"date":"2024-03-06T11:32:40","date_gmt":"2024-03-06T11:32:40","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=3541"},"modified":"2024-03-06T11:32:40","modified_gmt":"2024-03-06T11:32:40","slug":"basics-of-file-handling-in-c","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/basics-of-file-handling-in-c\/","title":{"rendered":"Basics Of File Handling In C"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><p>Table of Contents<\/p><nav><ul><li ><a href=\"#basics-of-file-handling-in-c\"> Basics Of File Handling In C<\/a><\/li><li ><a href=\"#why-do-we-need-file-handling-in-c\">Why do we need File Handling in C?<\/a><\/li><li ><a href=\"#types-of-files-in-c\">Types of Files in C<\/a><\/li><li ><a href=\"#1-text-files\">1.Text Files<\/a><\/li><li ><a href=\"#2-binary-files\">2. Binary Files<\/a><\/li><li ><a href=\"#c-file-operations\">C File Operations<\/a><\/li><li ><a href=\"#functions-for-c-file-operations\">Functions for C File Operations<\/a><ul><li ><a href=\"#file-pointer-in-c\">File Pointer in C<\/a><\/li><\/ul><\/li><li ><a href=\"#open-a-file-in-c\">Open a File in C<\/a><ul><li ><a href=\"#parameters\">Parameters<\/a><\/li><li ><a href=\"#return-value\">Return Value<\/a><\/li><\/ul><\/li><li ><a href=\"#file-opening-modes-in-c\">File opening modes in C <\/a><ul><li ><a href=\"#example-of-opening-a-file\">Example of Opening a File<\/a><\/li><\/ul><\/li><li ><a href=\"#create-a-file-in-c\">Create a File in C<\/a><\/li><li ><a href=\"#reading-from-a-file\">Reading From a File<\/a><\/li><li ><a href=\"#write-to-a-file\">Write to a File<\/a><ul><li ><a href=\"#example\">Example<\/a><\/li><\/ul><\/li><li ><a href=\"#closing-a-file\">Closing a File<\/a><\/li><li ><a href=\"#examples-of-file-handing-in-c\">Examples of File Handing in C<\/a><ul><li ><a href=\"#example-1-program-to-create-a-file-write-in-it-and-close-the-file\">Example 1:\u00a0Program to Create a File, Write in it, And Close the File<\/a><\/li><li ><a href=\"#example-2-program-to-open-a-file-read-from-it-and-close-the-file\">Example 2:\u00a0Program to Open a File, Read from it, And Close the File<\/a><\/li><\/ul><\/li><li ><a href=\"#read-and-write-in-a-binary-file\">Read and Write in a Binary File<\/a><\/li><li ><a href=\"#write-to-a-binary-file\">Write to a Binary File<\/a><\/li><li ><a href=\"#reading-from-binary-file\">Reading from Binary File<\/a><\/li><li ><a href=\"#fseek-in-c\">fseek() in C<\/a><\/li><li ><a href=\"#rewind-in-c\">Rewind() in C<\/a><\/li><li ><a href=\"#more-functions-for-c-file-operations\">More Functions for C File Operations <\/a><\/li><li ><a href=\"#faq-basics-of-file-handling-in-c\">FAQ- Basics of File Handling in C<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"basics-of-file-handling-in-c\"> Basics Of File Handling In C<\/h2>\n\n\n\n<p>File handing in C is the process where we can create, open, read, write, and close operations on a file. C language also has different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"why-do-we-need-file-handling-in-c\">Why do we need File Handling in C?<\/h2>\n\n\n\n<p>The essence of why file handling is crucial in programming, especially in the software industry.<\/p>\n\n\n\n<p>File Handling Importance:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Reusability:<\/strong><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Data stored in files can be accessed, updated, and deleted, offering high reusability.<\/li>\n<\/ul>\n\n\n\n<p>    2. <strong>Portability:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Files can be transferred within a computer system without losing data, minimizing the risk of flawed coding.<\/li>\n<\/ul>\n\n\n\n<p>   3.  <strong>Efficiency<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>File handling allows efficient access to specific parts of a file, saving time and reducing the chance of errors, especially with large datasets.<\/li>\n<\/ul>\n\n\n\n<p>  4. <strong>Storage Capacity:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Files enable the storage of large amounts of data without the need to manage everything simultaneously within a program.<\/li>\n<\/ul>\n\n\n\n<p>In summary, file handling enhances the flexibility, portability, efficiency, and storage capacity of programs, making it a fundamental aspect of software development in handling and managing data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"types-of-files-in-c\">Types of Files in C<\/h2>\n\n\n\n<p>A file is divided into two types depending on the way the file can store data. Those two types are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Text Files<\/strong><\/li>\n\n\n\n<li><strong>Binary File<\/strong><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-text-files\">1.Text Files<\/h2>\n\n\n\n<p> An overview of text files and their characteristics. Here&#8217;s a concise summary:<\/p>\n\n\n\n<p>Text File Characteristics:<\/p>\n\n\n\n<p>  a. <strong>Data Format:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Contains data in the form of ASCII characters.<\/li>\n<\/ul>\n\n\n\n<p>  b. <strong>Line Termination<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Each line ends with a new line character (<code>'\\n'<\/code>).<\/li>\n<\/ul>\n\n\n\n<p>  c.<strong>Readability:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Readable and writable by any text editor.<\/li>\n<\/ul>\n\n\n\n<p>  d. <strong>File Extension:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Typically stored with a .txt file extension.<\/li>\n<\/ul>\n\n\n\n<p>  e. <strong>Versatility:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Commonly used to store a stream of characters.<\/li>\n<\/ul>\n\n\n\n<p>  f. <strong>Source Code Storage:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Can be utilized to store source code.<\/li>\n<\/ul>\n\n\n\n<p>In essence, text files are versatile and widely compatible for storing and accessing human-readable data, making them a standard choice for various applications, including storing source code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-binary-files\"><strong>2. Binary Files<\/strong><\/h2>\n\n\n\n<p>Binary File Characteristics:<\/p>\n\n\n\n<p>a .<strong>Data Format:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Contains data in binary form (0\u2019s and 1\u2019s), mirroring the storage in main memory.<\/li>\n<\/ul>\n\n\n\n<p>b. <strong>Creation Source:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Created programmatically from within a program.<\/li>\n<\/ul>\n\n\n\n<p>c. <strong>Readability <\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Contents can only be read by a program, not easily readable by humans.<\/li>\n<\/ul>\n\n\n\n<p> d. <strong>Security<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>More secure due to the non-human-readable nature of binary data.<\/li>\n<\/ul>\n\n\n\n<p>e. <strong>File Extension:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Generally stored with a .bin file extension.<\/li>\n<\/ul>\n\n\n\n<p>Binary files are preferred for their efficient representation of data in a manner similar to main memory storage, and their increased security due to the non-human-readable format. They are commonly used for storing data that is meant to be processed by programs rather than viewed directly by users.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"c-file-operations\">C File Operations<\/h2>\n\n\n\n<p>C File Operations:<\/p>\n\n\n\n<p>a. <strong>Creating a New File:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>fopen()<\/code> with attributes like &#8220;a&#8221;, &#8220;a+&#8221;, &#8220;w&#8221;, or &#8220;w+&#8221; to create a new file.<\/li>\n<\/ul>\n\n\n\n<p>b.<strong>Opening an Existing File<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>fopen()<\/code> to open an existing file.<\/li>\n<\/ul>\n\n\n\n<p>c. <strong>Reading from File:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>fscanf()<\/code> or <code>fgets()<\/code> to read data from a file.<\/li>\n<\/ul>\n\n\n\n<p>d.<strong>Writing to a File:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>fprintf()<\/code> or <code>fputs()<\/code> to write data to a file.<\/li>\n<\/ul>\n\n\n\n<p>e. <strong>Moving to a Specific Location in a File:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>fseek()<\/code>, <code>rewind()<\/code> to navigate to a specific position in a file.<\/li>\n\n\n\n<li>f.<strong>Closing a File:<\/strong><\/li>\n<\/ul>\n\n\n\n<p>f.<strong>Closing a File:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>fclose()<\/code> to close the file after operations are completed.<\/li>\n<\/ul>\n\n\n\n<p>These operations collectively allow manipulation, reading, and writing of data to and from files in the C programming language, providing flexibility in handling data persistence.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"functions-for-c-file-operations\"><strong>Functions for C File Operations<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"file-pointer-in-c\">File Pointer in C<\/h3>\n\n\n<div class=\"gb-container gb-container-ee65780f\">\n\n<p>In C programming, a file pointer is like a marker that points to a specific spot in an open file. This pointer is essential for carrying out file operations such as reading, writing, and closing. To declare a file pointer variable, we use the FILE macro, which is defined in the header file. The file pointer essentially helps us keep track of where we are in a file, enabling us to perform different operations effectively.<\/p>\n\n\n\n<p>Syntax of File Pointer<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FILE* pointer_name;\n<\/code><\/pre>\n\n<\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"open-a-file-in-c\"><strong>Open a File in C<\/strong><\/h2>\n\n\n\n<p>For opening a file in C, the&nbsp;<a href=\"https:\/\/www.geeksforgeeks.org\/c-fopen-function-with-examples\/\" rel=\"nofollow noopener\" target=\"_blank\">fopen()&nbsp;<\/a>works  with the filename or file path along with the required access modes.<\/p>\n\n\n\n<p><strong>Syntax of fopen()<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FILE* fopen(const char *file_name, const char *access_mode);\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"parameters\">Parameters<\/h3>\n\n\n\n<p>The term &#8220;file_name&#8221; refers to the name of a file. If the file is in the same directory as the source file, you only need to provide its name. Otherwise, if the file is located in a different directory, you should include the full path to the file.<\/p>\n\n\n\n<p>The &#8220;access_mode&#8221; is a specification indicating the purpose for which the file is being opened. It signifies the type of operation you want to perform on the file, whether it&#8217;s for reading, writing, or both.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"return-value\">Return Value<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>If the file is successfully opened, the program receives a file pointer, which is like a reference allowing it to interact with the contents of the file.<\/li>\n\n\n\n<li>If the attempt to open the file fails for some reason, the program gets a special value called NULL. This indicates that the file wasn&#8217;t opened, and the program needs to handle this situation accordingly<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"file-opening-modes-in-c\">File opening modes in C<br><\/h2>\n\n\n\n<p>File opening modes or access modes which would grand allowed operations on the file to be opened. Hence,they are passed as an argument to the fopen() function. Commonly used file access modes are listed below:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Opening Modes<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><strong>r<\/strong><\/td><td>It function to Searches file. If the file is opened successfully fopen( ) loads it into memory and would  sets up a pointer that points to the first character in it. If the file cannot be opened fopen( ), then  it will  returns NULL.<\/td><\/tr><tr><td><strong>rb<\/strong><\/td><td>&nbsp;This refers to Open the  reading in binary mode. If the file does not exist, then  fopen( ) returns NULL.<\/td><\/tr><tr><td><strong>w<\/strong><\/td><td>This refers to Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn\u2019t exist, a new file is created. Returns NULL, if unable to open the file.<\/td><\/tr><tr><td><strong>wb<\/strong><\/td><td>This refers to Open for writing in binary mode. If the file exists and their  contents are overwritten. If the file does not exist, it will be created.<\/td><\/tr><tr><td><strong>a<\/strong><\/td><td>This indicates to Searche file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that would points to the last character in it. It opens only in the append mode. If the file doesn\u2019t exist, a new file would be made. Returns NULL, if unable to open the file.<\/td><\/tr><tr><td><strong>ab<\/strong><\/td><td>&nbsp;Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created.<\/td><\/tr><tr><td><strong>r+<\/strong><\/td><td>Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the first character in it. Returns NULL, if unable to open the file.<\/td><\/tr><tr><td><strong>rb+<\/strong><\/td><td>&nbsp;This will Open for both reading and writing in binary mode. If the file does not exist, fopen( ) will returns NULL.<\/td><\/tr><tr><td><strong>w+<\/strong><\/td><td>This indicate Searches file. If the file exists, its contents are overwritten. If the file doesn\u2019t exist a new file is created. Returns NULL, if unable to open the file.<\/td><\/tr><tr><td><strong>wb+<\/strong><\/td><td>This will Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be formed.<\/td><\/tr><tr><td><strong>a+<\/strong><\/td><td>This refers to Searching file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. It opens the file in both reading and append mode. If the file doesn\u2019t exist, a new file is created. Returns NULL, if unable to open the file.<\/td><\/tr><tr><td><strong>ab+<\/strong><\/td><td>It will Open for both reading and appending in binary mode. If the file does not exist, it will be created.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>According to the file access mode given above , if you want to do operations on a binary file, then you have to append \u2018b\u2019 at the last. For example, instead of \u201cw\u201d, you have to use \u201cwb\u201d, instead of \u201ca+\u201d you have to use \u201ca+b\u201d.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example-of-opening-a-file\"><strong>Example of Opening a File<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C Program to illustrate file opening\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n \nint main()\n{\n    \/\/ file pointer variable to store the value returned by\n    \/\/ fopen\n    FILE* fptr;\n \n    \/\/ opening the file in read mode\n    fptr = fopen(\"filename.txt\", \"r\");\n \n    \/\/ checking if the file is opened successfully\n    if (fptr == NULL) {\n        printf(\"The file is not opened. The program will \"\n               \"now exit.\");\n        exit(0);\n    }\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>The file is not opened. The program will now exit.\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"create-a-file-in-c\">Create a File in C<\/h2>\n\n\n\n<p>The <code>fopen()<\/code> function not only opens existing files but can also create a new file if it doesn&#8217;t already exist. To achieve this, you use specific modes that allow file creation. These modes include &#8220;w,&#8221; &#8220;w+,&#8221; &#8220;wb,&#8221; &#8220;wb+,&#8221; &#8220;a,&#8221; &#8220;a+,&#8221; &#8220;ab,&#8221; and &#8220;ab+.&#8221; When you use one of these modes, the function opens the file for writing, and if the file doesn&#8217;t exist, a new one is created. This flexibility is useful when you want to handle both existing and new files in your program.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FILE *fptr;\nfptr = fopen(\"filename.txt\", \"w\");<\/code><\/pre>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n\n\/\/ C Program to create a file\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n \nint main()\n{\n    \/\/ file pointer\n    FILE* fptr;\n \n    \/\/ creating file using fopen() access mode \"w\"\n    fptr = fopen(\"file.txt\", \"w\");\n \n    \/\/ checking if the file is created\n    if (fptr == NULL) {\n        printf(\"The file is not opened. The program will \"\n               \"exit now\");\n        exit(0);\n    }\n    else {\n        printf(\"The file is created Successfully.\");\n    }\n   \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>The file is created Successfully.\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"reading-from-a-file\"><strong>Reading From a File<\/strong><\/h2>\n\n\n\n<p>In C, reading from a file is done using functions like <code>fscanf()<\/code> or <code>fgets()<\/code>. These functions perform similar operations to <code>scanf()<\/code> and <code>gets()<\/code>, but they have an additional parameter &#8211; the file pointer. This file pointer helps specify the file from which data should be read.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><a href=\"https:\/\/www.geeksforgeeks.org\/scanf-and-fscanf-in-c\/\" rel=\"nofollow noopener\" target=\"_blank\"><strong>fscanf()<\/strong><\/a><\/td><td>It will Use formatted string and variable arguments list to take input from a file.&nbsp;<\/td><\/tr><tr><td><a href=\"https:\/\/www.geeksforgeeks.org\/fgets-gets-c-language\/\" rel=\"nofollow noopener\" target=\"_blank\"><strong>fgets()<\/strong><\/a><\/td><td>It has Input the whole line from the file.<\/td><\/tr><tr><td><a href=\"https:\/\/www.geeksforgeeks.org\/fgetc-fputc-c\/\" rel=\"nofollow noopener\" target=\"_blank\"><strong>fgetc()<\/strong><\/a><\/td><td>It will Read a single character from the file.<\/td><\/tr><tr><td><strong>fgetw()<\/strong><\/td><td>It will Read a number from a file.<\/td><\/tr><tr><td><a href=\"https:\/\/www.geeksforgeeks.org\/fread-function-in-c\/\" rel=\"nofollow noopener\" target=\"_blank\"><strong>fread()<\/strong><\/a><\/td><td>It will Read the specified bytes of data from a binary file.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FILE * fptr; \nfptr = fopen(\u201cfileName.txt\u201d, \u201cr\u201d);\nfscanf(fptr, \"%s %s %s %d\", str1, str2, str3, &amp;year);\nchar c = fgetc(fptr);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"write-to-a-file\"><strong>Write to a File<\/strong><\/h2>\n\n\n\n<p>In C programming, writing to a file is accomplished using functions like <code>fprintf()<\/code> and <code>fputs()<\/code>, which are similar to the read operations but are used for writing data. These functions, like their read counterparts, also require a file pointer as an additional parameter to specify the target file.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Function<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><a href=\"https:\/\/www.geeksforgeeks.org\/fprintf-in-c\/\" rel=\"nofollow noopener\" target=\"_blank\"><strong>fprintf()<\/strong><\/a><\/td><td>It works Similar to printf(), this function use formatted string and varible arguments list to print output to the file.<\/td><\/tr><tr><td><a href=\"https:\/\/www.geeksforgeeks.org\/how-to-write-in-a-file-using-fputs-in-c\/\" rel=\"nofollow noopener\" target=\"_blank\"><strong>fputs()<\/strong><\/a><\/td><td>It will Prints the whole line in the file and a newline at the end.<\/td><\/tr><tr><td><a href=\"https:\/\/www.geeksforgeeks.org\/fgetc-fputc-c\/\" rel=\"nofollow noopener\" target=\"_blank\"><strong>fputc()<\/strong><\/a><\/td><td>It will Prints a single character into the file.<\/td><\/tr><tr><td><strong>fputw()<\/strong><\/td><td>It will Prints a number to the file.<\/td><\/tr><tr><td><strong>fwrite()<\/strong><\/td><td>This functions write the specified amount of bytes to the binary file.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code><span style=\"background-color: var(--gfg-grey-bg); color: rgb(39, 50, 57); font-family: Consolas, monospace; font-size: 12pt; letter-spacing: 0.162px;\">FILE *fptr ; <\/span><pre style=\"box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; border: 0px; font-size: 12pt; vertical-align: baseline; background-color: var(--gfg-grey-bg); border-radius: 10px; color: rgb(39, 50, 57); font-family: Consolas, monospace; text-wrap: wrap; overflow-wrap: break-word; letter-spacing: 0.162px;\"><span style=\"box-sizing: border-box; margin: 0px; padding: 0px; border: 0px; vertical-align: baseline;\">fptr = fopen(\u201cfileName.txt\u201d, \u201cw\u201d);<\/span><span style=\"box-sizing: border-box; margin: 0px; padding: 0px; border: 0px; vertical-align: baseline;\">fprintf(fptr, \"%s %s %s %d\", \"We\", \"are\", \"in\", 2012);<\/span><span style=\"box-sizing: border-box; margin: 0px; padding: 0px; border: 0px; vertical-align: baseline;\">fputc(\"a\", fptr);<\/span><\/pre><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"closing-a-file\"><strong>Closing a File<\/strong><\/h2>\n\n\n\n<p>The fclose() function is basically used to close the file. After successful file operations, you must always close a file to remove it from the memory.<\/p>\n\n\n\n<p>Syntax of fclose()<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fclose(file_pointer);\n<\/code><\/pre>\n\n\n\n<p>File_pointer is used to open the file<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FILE *fptr ;\nfptr= fopen(\u201cfileName.txt\u201d, \u201cw\u201d);\n---------- Some file Operations -------\nfclose(fptr);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"examples-of-file-handing-in-c\">Examples of File Handing in C<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example-1-program-to-create-a-file-write-in-it-and-close-the-file\"><strong>Example 1:<\/strong>&nbsp;Program to Create a File, Write in it, And Close the File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to Open a File,\n\/\/ Write in it, And Close the File\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n \nint main()\n{\n \n    \/\/ Declare the file pointer\n    FILE* filePointer;\n \n    \/\/ Get the data to be written in file\n    char dataToBeWritten&#91;50] = \"Skillvertex-A Computer \"\n                               \"Science Portal for Skill\";\n \n    \/\/ Open the existing file GfgTest.c using fopen()\n    \/\/ in write mode using \"w\" attribute\n    filePointer = fopen(\"GfgTest.c\", \"w\");\n \n    \/\/ Check if this filePointer is null\n    \/\/ which maybe if the file does not exist\n    if (filePointer == NULL) {\n        printf(\"GfgTest.c file failed to open.\");\n    }\n    else {\n \n        printf(\"The file is now opened.\\n\");\n  \/\/ Write the dataToBeWritten into the file\n        if (strlen(dataToBeWritten) &gt; 0) {\n \n            \/\/ writing in the file using fputs()\n            fputs(dataToBeWritten, filePointer);\n            fputs(\"\\n\", filePointer);\n        }\n \n        \/\/ Closing the file using fclose()\n        fclose(filePointer);\n \n        printf(\"Data successfully written in file \"\n               \"GfgTest.c\\n\");\n        printf(\"The file is now closed.\");\n    }\n   \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>The file is now opened.\nData successfully written in file GfgTest.c\nThe file is now closed.<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example-2-program-to-open-a-file-read-from-it-and-close-the-file\"><strong>Example 2:<\/strong>&nbsp;Program to Open a File, Read from it, And Close the File<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to Open a File,\n\/\/ Read from it, And Close the File\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n \nint main()\n{\n \n    \/\/ Declare the file pointer\n    FILE* filePointer;\n \n    \/\/ Declare the variable for the data to be read from\n    \/\/ file\n    char dataToBeRead&#91;50];\n \n    \/\/ Open the existing file GfgTest.c using fopen()\n    \/\/ in read mode using \"r\" attribute\n    filePointer = fopen(\"GfgTest.c\", \"r\");\n \n    \/\/ Check if this filePointer is null\n    \/\/ which maybe if the file does not exist\n    if (filePointer == NULL) {\n        printf(\"GfgTest.c file failed to open.\");\n    }\n    else {\n \n        printf(\"The file is now opened.\\n\");\n \n        \/\/ Read the dataToBeRead from the file\n        \/\/ using fgets() method\n        while (fgets(dataToBeRead, 50, filePointer)\n               != NULL) {\n \n            \/\/ Print the dataToBeRead\n            printf(\"%s\", dataToBeRead);\n        }\n \n        \/\/ Closing the file using fclose()\n        fclose(filePointer);\n \n        printf(\n            \"Data successfully read from file GfgTest.c\\n\");\n        printf(\"The file is now closed.\");\n    }\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>The file is now opened.\nSkillvertex-A Computer Science Portal for Skill\nData successfully read from file GfgTest.c\nThe file is now closed.<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"read-and-write-in-a-binary-file\">Read and Write in a Binary File<\/h2>\n\n\n\n<p><strong>Opening a Binary File<\/strong><\/p>\n\n\n\n<p>This will help to  open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in the fopen() function. It will also use the .bin file extension in the binary filename.<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fptr = fopen(\"filename.bin\", \"rb\");\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"write-to-a-binary-file\">Write to a Binary File<\/h2>\n\n\n\n<p>We use the  fwrite() function to write data to a binary file. The data will be  written to the binary file in the from of bits (0\u2019s and 1\u2019s).<\/p>\n\n\n\n<p><strong>Syntax of fwrite()<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);\n<\/code><\/pre>\n\n\n\n<p><strong>Parameters:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>ptr<\/code>:<\/strong> This is a pointer to the block of memory containing the data you want to write.<\/li>\n\n\n\n<li><strong><code>size<\/code>:<\/strong> Specifies the size of each element to be written, measured in bytes.<\/li>\n\n\n\n<li><strong><code>nmemb<\/code>:<\/strong> Represents the number of elements you want to write to the file.<\/li>\n\n\n\n<li><strong><code>file_pointer<\/code>:<\/strong> This is the FILE pointer that points to the output file stream. It indicates the file where the data should be written.<\/li>\n<\/ul>\n\n\n\n<p>Rerurn Value<\/p>\n\n\n\n<p>Number of objects written.<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to write to a Binary file using fwrite()\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nstruct threeNum {\n    int n1, n2, n3;\n};\nint main()\n{\n    int n;\n    \/\/ Structure variable declared here.\n    struct threeNum num;\n    FILE* fptr;\n    if ((fptr = fopen(\"C:\\\\program.bin\", \"wb\")) == NULL) {\n        printf(\"Error! opening file\");\n        \/\/ If file pointer will return NULL\n        \/\/ Program will exit.\n        exit(1);\n    }\n    int flag = 0;\n    \/\/ else it will return a pointer to the file.\n    for (n = 1; n &lt; 5; ++n) {\n        num.n1 = n;\n        num.n2 = 5 * n;\n        num.n3 = 5 * n + 1;\n        flag = fwrite((&amp;num, sizeof(struct threeNum), 1,\n                      fptr);\n    }\n \n    \/\/ checking if the data is written\n    if (!flag) {\n        printf(\"Write Operation Failure\");\n    }\n    else {\n        printf(\"Write Operation Successful\");\n    }\n \n    fclose(fptr);\n   \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Write Operation Successful\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"reading-from-binary-file\">Reading from Binary File<\/h2>\n\n\n\n<p>The fread() function is  used to read data from a binary file in C. The data is read from the file in the same form as it will be stored i.e. binary form.<\/p>\n\n\n\n<p>Syntax<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file_pointer);\n<\/code><\/pre>\n\n\n\n<p>Parameters<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>ptr<\/code>:<\/strong> This is a pointer to the block of memory where the read data will be stored.<\/li>\n\n\n\n<li><strong><code>size<\/code>:<\/strong> Specifies the size of each element to be read, measured in bytes.<\/li>\n\n\n\n<li><strong><code>nmemb<\/code>:<\/strong> Represents the number of elements you want to read from the file.<\/li>\n\n\n\n<li><strong><code>file_pointer<\/code>:<\/strong> This is the FILE pointer that points to the input file stream. It indicates the file from which data should be read.<\/li>\n<\/ul>\n\n\n\n<p>Return Value<\/p>\n\n\n\n<p>Number of Objects that will be written<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C Program to Read from a binary file using fread()\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nstruct threeNum {\n    int n1, n2, n3;\n};\nint main()\n{\n    int n;\n    struct threeNum num;\n    FILE* fptr;\n    if ((fptr = fopen(\"C:\\\\program.bin\", \"rb\")) == NULL) {\n        printf(\"Error! opening file\");\n        \/\/ If file pointer will return NULL\n        \/\/ Program will exit.\n        exit(1);\n    }\n    \/\/ else it will return a pointer to the file.\n    for (n = 1; n &lt; 5; ++n) {\n        fread(&amp;num, sizeof(struct threeNum), 1, fptr);\n        printf(\"n1: %d\\tn2: %d\\tn3: %d\\n\", num.n1, num.n2,\n               num.n3);\n    }\n    fclose(fptr);\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>n1: 1   n2: 5   n3: 6\nn1: 2   n2: 10  n3: 11\nn1: 3   n2: 15  n3: 16\nn1: 4   n2: 20  n3: 21<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fseek-in-c\"><strong>fseek() in C<\/strong><\/h2>\n\n\n\n<p>When dealing with a file containing multiple records, finding a specific record by looping through all the preceding ones can be inefficient in terms of both memory and time. To address this, we use the <code>fseek()<\/code> function in C, which efficiently moves the file cursor to a specified record.<\/p>\n\n\n\n<p>With <code>fseek()<\/code>, we can directly navigate to the desired record in the file, reducing the need to iterate through all preceding records. This not only saves memory but also speeds up the operation, making it a more efficient way to access specific data within a file<\/p>\n\n\n\n<p>Syntax<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int fseek(FILE *ptr, long int offset, int pos);\n<\/code><\/pre>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n\n\/\/ C Program  to demonstrate the use of fseek() in C\n#include &lt;stdio.h&gt;\n \nint main()\n{\n    FILE* fp;\n    fp = fopen(\"test.txt\", \"r\");\n \n    \/\/ Moving pointer to end\n    fseek(fp, 0, SEEK_END);\n \n    \/\/ Printing position of pointer\n    printf(\"%ld\", ftell(fp));\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>81<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"rewind-in-c\">Rewind() in C<\/h2>\n\n\n\n<p>The <code>rewind()<\/code> function in C is used to reset the file pointer, bringing it back to the beginning of the file. This function is convenient when you specifically want the file pointer to be positioned at the start of the file. It serves as an alternative to using <code>fseek()<\/code> for this purpose.<\/p>\n\n\n\n<p>Symtax<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rewind (file_pointer);\n<\/code><\/pre>\n\n\n\n<p>Example<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ C program to illustrate the use of rewind\n#include &lt;stdio.h&gt;\n \nint main()\n{\n    FILE* fptr;\n    fptr = fopen(\"file.txt\", \"w+\");\n    fprintf(fptr, \"Skillvertex \\n\");\n \n    \/\/ using rewind()\n    rewind(fptr);\n \n    \/\/ reading from file\n    char buf&#91;50];\n    fscanf(fptr, \"%&#91;^\\n]s\", buf);\n \n    printf(\"%s\", buf);\n \n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Skillvertex<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"more-functions-for-c-file-operations\">More Functions for C File Operations<br><\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Functions<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td>fopen()<\/td><td>This function willl create a file or to open a file.<\/td><\/tr><tr><td>fclose()<\/td><td> fclose() will  close a file.<\/td><\/tr><tr><td>fgets()<\/td><td>This function  will read a file.<\/td><\/tr><tr><td>fprintf()<\/td><td>This function  will write blocks of data into a file.<\/td><\/tr><tr><td>fscanf()<\/td><td>fscanf() willread blocks of data from a file.<\/td><\/tr><tr><td>getc()<\/td><td>This function will  read a single character to a file.<\/td><\/tr><tr><td>putc()<\/td><td>This function will write a single character to a file.<\/td><\/tr><tr><td>fseek()<\/td><td>This function will set the position of a file pointer to a mentioned location.<\/td><\/tr><tr><td>ftell()<\/td><td> ftell() will return the current position of a file pointer.<\/td><\/tr><tr><td>rewind()<\/td><td>rewind() will set the file pointer to the beginning of a file.<\/td><\/tr><tr><td>putw()<\/td><td>It is used to write an integer to a file.<\/td><\/tr><tr><td>getw()<\/td><td>This function will  read an integer from a file.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-basics-of-file-handling-in-c\">FAQ- Basics of File Handling in C<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1700034835568\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1.What is the basic of file handling in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. In C programming, file handling is about how a program saves its data into a file. It&#8217;s like storing information in a place that can be easily accessed later. This stored data can be used again in different parts of the program whenever needed.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1700034839949\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2. How to use files in C? <\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. <strong>Create a variable:<\/strong> Make a variable of type &#8220;FILE*&#8221;.<br \/><strong>Open the file:<\/strong> Use the &#8220;fopen&#8221; function to open the file and assign it to the variable.<br \/><strong>Check if successful:<\/strong> Verify if the file was opened successfully by checking if the variable is equal to NULL.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1700034845998\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. How to write file in C?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. <strong>Creating a new file:<\/strong> Use <code>fopen()<\/code> with attributes like &#8220;a&#8221;, &#8220;a+&#8221;, &#8220;w&#8221;, or &#8220;w+&#8221;.<br \/><strong>Opening an existing file:<\/strong> Simply use <code>fopen()<\/code>.<br \/><strong>Reading from a file:<\/strong> Use <code>fscanf()<\/code> or <code>fgets()<\/code>.<br \/><strong>Writing to a file:<\/strong> Use <code>fprintf()<\/code> or <code>fputs()<\/code>.<br \/><strong>Moving to a specific location in a file:<\/strong> Utilize <code>fseek()<\/code> or <code>rewind()<\/code>.<br \/><strong>Closing a file:<\/strong> Employ <code>fclose()<\/code>.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n\n<p><a href=\"https:\/\/www.geeksforgeeks.org\/c-file-handling-question-1\/\" rel=\"nofollow noopener\" target=\"_blank\"><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Basics Of File Handling In C File handing in C is the process where we can create, open, read, write, and close operations on a file. C language also has different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Why do &#8230; <a title=\"Basics Of File Handling In C\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/basics-of-file-handling-in-c\/\" aria-label=\"More on Basics Of File Handling In C\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":5414,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[568],"class_list":["post-3541","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-basics-of-file-handling-in-c","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3541","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=3541"}],"version-history":[{"count":8,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3541\/revisions"}],"predecessor-version":[{"id":7943,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/3541\/revisions\/7943"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/5414"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=3541"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=3541"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=3541"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}