Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is fwrite() in C?
3.
Syntax of fwrite() function in C
4.
Parameters of fwrite() function in C
5.
Return Value of fwrite() function in C
6.
Example of fwrite() function in C
6.1.
Creating a text file with a particular message
6.1.1.
Output
6.2.
Creating a Structure for Student Details
6.2.1.
Output
6.3.
Creating an Array of Structures
6.3.1.
Output
7.
Exceptions of fwrite() Function in C
8.
Frequently Asked Questions
8.1.
What makes write and fwrite different from one another?
8.2.
Why use fwrite in C?
8.3.
How to write to a file using fwrite in C?
8.4.
Does fwrite overwrite C?
8.5.
How come fwrite is quicker than write?
8.6.
What distinguishes the C fread/fwrite and fscanf functions? 
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

fwrite() Function in C

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this article, we’ll see about a function fwrite in C language which is used by programmers to create such files. You’ll learn about the syntax and parameters of fwrite c. 

fwrite c

Apart from it, we’ll write the program to create a file too. So without any further ado, let’s get started with our discussion! 

What is fwrite() in C?

The fwrite() is a function in C programming language. It is a function that is used to create a file for data storage, updation, insertion, and deletion. It is a library function of C which is used to create such files. When the program is compiled successfully the file is created in the system with the desired data entry by the user.

Apart from creating files using fwrite c, you can use it for many applications. It can be for scientific computing, data processing, multimedia programming, etc. There is also fread() function in C, it reads count elements of data from the file, each size bytes long.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of fwrite() function in C

The syntax of fwrite C is given below:

size_t fwrite(void *ptr, size_t size, size_t count, FILE *str);

The syntax is a set of rules for the structure of the program. 

Parameters of fwrite() function in C

Let us look at the parameters that we pass to the fwrite C function. Following are the described parameters of the fwrite C function.

The different types of parameters we used in the above syntax of fwrite() function in C:

Parameters

About

ptr It is a void-type pointer. It points to the block of memory.  It is a pointer to the space where data items are to be written.
size It indicates the size in bytes of each element that needed to be read.
count It indicates the number of elements to write.
str It is a pointer to the FILE object creating the file to write on.

Now let us look at what fwrite function in C returns.

Return Value of fwrite() function in C

When you have successfully executed your code. You will get the return count of the number of items successfully written to the file. If you encounter an error, it returns a number less than count.

You should note that the two arguments (size and count) and return value of fwrite() is of type size_t. You’ll probably get the size_t as unsigned int.

Example of fwrite() function in C

Following are some examples by using the fwrite C.

Creating a text file with a particular message

In this example, we will create a file named codingninjas.txt. In this file, we will save the text in the file “Hello Ninjas! Welcome to Coding Ninjas”. This will create a file in the system when we compile our program.

Let us write our program in C language:

#include <stdio.h>
#include <string.h>

int main() 
{

	// Creating a filepointer
	FILE *file;
	
	// Saving the text message
	char greeting[] = "Hello Ninjas! Welcome to Coding Ninjas";
	
	// Creating a file with name codingninjas
	file = fopen("codingninjas.txt", "w");
	
	// If file is not created
	if (file == NULL)
	{
		printf("Some Error occurred while opening file.");
	}
	
	else
	{
		fwrite(greeting, sizeof(char), strlen(greeting), file);
	}
	
	// Closing the file
	fclose(file);
	
	// Printing the message for user
	printf(" Your File has been created.\n");
	
	return 0;
}

Output

Program output

After the successful compilation of the program. You can see the file named codingninjas.txt in the document folder of the system. The file will store the text which we have written in our program. When the user opens the file, the file will contain the following data:

Hello Ninjas! Welcome to Coding Ninjas
creating text file

Creating a Structure for Student Details

In this example, we will create a file named students.txt. We will be creating a structure of students with details like name, RollNo, and educator. We will be storing data as:

Name: Abhishek    RollNo: 65    Educator: CodingNinjas
 

Let us write our program in C language:

#include <stdio.h>
#include <string.h>

struct Student 
{
    // Creating structure named student
    char name[50];
    int RollNo;
    char educator[50];
};

int main() 
{

    // Creating a file pointer
    FILE *file = fopen("students.txt", "w");

    // Entering the details
    struct Student s = {"Abhishek", 65, "Coding Ninjas"};

    // If opening the file fails
    if (file == NULL) 
    {
        printf("Some error occurred while opening the file!\n");
    }

     else
     {
    	// Write the student details in the file
    	fwrite(&s, sizeof(struct Student), 1, file);
     }

    // Close the file
    fclose(file);

    // Printing the message for user
    printf("Welcome, Your data has been created!\n");

    return 0;
}

Output

Program output

After the successful compilation of the program. You can see the file named students.txt in the document folder of the system. The file will be storing the text which we written in our program. When the user opens the file, the file will contain the following data:

Abhishek    A    Coding Ninjas
creating text file

Creating an Array of Structures

In this example, we will create a file named StudentArray.txt. We will be creating a array of structures of students will its details like Name and Rollno. We will be storing data as:

Student, Rollno = (Sarthak, 65), (Vaibhav, 66)
 

Let us write our program in C language:

#include <stdio.h>
#include <string.h>

// Creating structure named student
struct student 
{
	char name[20];
	int Roll;
};

int main()
{

   // Entering the details
   struct student s[] =
   {{"Sarthak", 65}, {"Vaibhav", 66}};

   // Creating a file pointer
   FILE *file;

   // opening the file in write mode
   file = fopen("StudentArray.txt", "w");

   // If file is not created
   if(file == NULL) 
   {
    printf("Some error occurred");
   }
   
    // If file is created successfully
   fwrite(&s, sizeof(s), 1, file);

   // closing the file
   fclose(file);
   
   // Printing the message for user
   printf(" Your File has been created.\n");
   
   return 0;
}

Output

Program output

After the successful compilation of the program. You can see the file named StudentArray.txt in the folder of the system. The file location will be the same as shown in the above two examples. The file will be storing the data which we wrote in our program. When the user opens the file, the file will contain the following data:

text file data

Also see, Short int in C Programming

Exceptions of fwrite() Function in C

The fwrite() function in C writes data to a file stream. Exceptions may occur due to insufficient disk space, permissions, or hardware failures, leading to data loss or corruption. Handling these exceptions ensures robust file writing operations.

Frequently Asked Questions

What makes write and fwrite different from one another?

Fwrite writes to a FILE*, which is a stdio stream that may or may not be buffered. The ISO C standard makes it clear. Additionally, fwrite is somewhat thread-safe on POSIX systems. The POSIX standard describes write, a lower-level API based on file descriptors.

Why use fwrite in C?

Efficiently writes data to files, useful for saving structured data or binary files in C programs.

How to write to a file using fwrite in C?

Use fwrite function with parameters specifying data, size, count, and file stream.

Does fwrite overwrite C?

No, fwrite writes data to files without overwriting the C program itself; it operates on file streams.

How come fwrite is quicker than write?

Due to the overhead associated with performing a single kernel call, fwrite is faster for small (for example, line-at-a-time) byte counts. Because write doesn't bother with buffering and requires the kernel in both situations, it is faster for large (block I/O) byte counts.

What distinguishes the C fread/fwrite and fscanf functions? 

The main distinction between fread/fwrite and fscanf are for binary input and output files. We use the fread and fwrite functions. While formatted data from a file is read using the fscanf() function.

Conclusion

This article briefly discussed the fwrite c. We have discussed the example and solutions. You can check out our other blogs to enhance your knowledge:

You can refer to our guided paths on the Coding Ninjas Studio platform. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc.

We hope this blog helped you understand the fwrite c. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Happy Learning!!

Previous article
fread C
Next article
What is Include Stdio in C/C++?
Live masterclass