A program to Create, Write and Close a file in C language

A program to Create, Write and Close a file in C language

In the C programming language, to Create, Write and Close a file you need to;

1. Specify a pointer or the reference to the space in memory where the file will be stored, like;

FILE *filepointer;

 

2. Use the file creation function, fopen() and store it in the file pointer, like;

filepointer = fopen()

 

3. Inside the fopen() function, specify the file name or location and file name, as well as the mode in which the file will be opened. Modes can be; ‘r’ – read, ‘w’ – write, ‘a’ – append, ‘w+’ – read and write, etc.

filepointer = fopen("filename", "mode")

 

4. Close it using the close function, fclose(), which takes the open file’s pointer as the argument;

fclose(filepointer)

 

Below is the full code to achieve the above;

#include <stdio.h>
#include <stdlib.h>

int main()
{
  // declare file pointer to memory location
  FILE *filepointer;
  
  // create a file named filename.txt in write 'w' mode for writing
  filepointer = fopen("filename.txt","w");
  
  // write text data to the .txt file
  fputs("Example text to store in the file we created!", filepointer);
  
  // close file to save the data we entered
  fclose(fptr);
  
  return 0;
}

 

A program to Create, Write and Close a file in C language
C | thetqweb