Write File in C


In C, you can use the standard library function fopen() to open a file, and then use the function fwrite() or fprintf() to write to the file.
Here is an example of how to write to a file called "sample.txt" using the fprintf() function:

This program demonstrates how to write to a file in C using the fopen() and fprintf() functions.

  • The program starts by including the stdio.h header file, which contains the declarations of the functions used in the program.
  • In the main function, the program declares a file pointer "fp". The fopen() function is used to open the file "sample.txt" in append mode and assigns the returned pointer to the file pointer "fp".
  • The append mode is used to add new data to the end of the file without truncating it, unlike the write mode that truncates the file to 0 bytes and overwrites it with the new data.
  • The fprintf() function is used to write the given string "Stanley" to the file. The fprintf() function takes two arguments: a pointer to the file and a format string.
  • Once all the data is written to the file, the program closes the file using the fclose() function and returns 0 to indicate that the program has executed successfully.
  • It's worth noting that if the file does not exist, the fopen function will create it.

Source Code

//Write a File
#include<stdio.h>
int main()
{
   FILE *fp;
   //fp=fopen("sample.txt","w");
   fp=fopen("sample.txt","a");
   fprintf(fp,"Stanley\n");
   fclose(fp);
    return 0;
}
 
To download raw file Click Here

Output

Before Write File

C Program - Write File

After Write File

C Program - Write File


List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C