C program to create a file and store information in it. In this article, I will explain, how to create a file in C programming and also write data in it. If you are not familiar with the file handling function, you should read the below article.
Learn file handling in C, in a few hours.
Example C Program to Create a File & Store Information:
In this code, I am creating the file in write mode using the fopen function. If the file opened successfully, then code asking input from the user and store it in created file.
#include <stdio.h> //Maximum size of the array #define MAX_SIZE 200 int main() { //file pointer FILE *fp = NULL; char buffer[MAX_SIZE] = {0}; //create the file fp = fopen("aticleworld.txt", "w"); if(fp == NULL) { printf("Error in creating the file\n"); exit(1); } //Get input from the user printf("Enter data which you want to store = "); if(fgets(buffer,MAX_SIZE,stdin) == NULL) { printf("Error in reading the input data\n"); //close the file fclose(fp); exit(1); } //Write the buffer in file fwrite(buffer, sizeof(buffer[0]), MAX_SIZE, fp); //close the file fclose(fp); printf("File has been created and saved successfully\n"); return 0; }
Output:
Code Analysis:
In the above c example, first, I have created the file (“aticleworld.txt”) using the “w” mode and get the file pointer. Using the if condition I am verifying that file is created successfully or not.
//create the file fp = fopen("aticleworld.txt", "w"); if(fp == NULL) { printf("Error in creating the file\n"); exit(1); }
After creating the file successfully, I have used fgets to read the input data and store it in a character array. I have also used the if condition to check whether fgets reads input data without error or not.
if(fgets(buffer,MAX_SIZE,stdin) == NULL) { printf("Error in reading the input data\n"); //close the file fclose(fp); exit(1); }
In the last, I have used fwrite to write the read data in the created file and close the file using fclose function. You can also see the article “How to use fwrite in C“.
//Write the buffer in file fwrite(buffer, sizeof(buffer[0]), MAX_SIZE, fp); //close the file fclose(fp);
Recommended Articles for you:
- Use of fgetc() function in C?
- How to use fputc() in C?
- You should know fgets() in C?
- fputs() in C?
- Use of fread() in C?
- How to use fwrite() in C?
- How to use fopen() in C?
- Use of if condition in C programs.
- Dangling, Void , Null and Wild Pointer.
- How to use fgets() in C?
- C program to convert uppercase to lowercase and vice versa in file
- File handling in C, In a few hours.
- C program to display its own source code as output
- How to use fwrite in C.
- C program to compare two files contents.
- Student Record System Project in C.
- C Program to Create a File & Store Information
- 100 C interview Questions.