Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to write the data in File.

C Code Example — File Handling Programs

ADVERTISEMENT

C Program to write the data in File.

Objective

Write a C program to write a string of data into a File character by character.

Algorithm / Approach

  1. Create a FILE pointer: FILE *fptr.
  2. Open a file in Write mode: fptr = fopen("prowess.txt", "w").
  3. Check if the file opened successfully (fptr != NULL).
  4. Read a string from the user.
  5. Loop through the string and use putc(text[i], fptr) to write each character to the file.
  6. Close the file using fclose(fptr).
main.c
#include<stdio.h>
int main( ) {
 FILE *fptr;
 char *text;
 fptr = fopen("prowess.txt","w");
 if(fptr != NULL) {
  printf("Enter text here: ");
  gets(text);
 for(i=0; text[i]!='\0'; i++) {
     putc(text[i],fptr);
  }
  printf("Data Saved!!");
  return 0;
}

Expected Output

Enter text here :
 C is a simple language
 Data Saved!!

Explanation of the Program

  • File handling in C requires a File Pointer. The fopen() function links this pointer to a physical file on your hard drive.
  • The "w" mode stands for Write. If the file doesn't exist, C will create it. If it already exists, C will completely erase its contents before writing the new data.

Complexity

Time Complexity O(n) - Where n is the string length.
Space Complexity O(n) - To hold the string in memory.

Common Mistakes

  • Forgetting to declare the loop counter i before using it in the for loop.
  • Forgetting to close the file with fclose(fptr) at the end of the program, which can cause data to not be saved properly.
ADVERTISEMENT