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
- Create a
FILEpointer:FILE *fptr. - Open a file in Write mode:
fptr = fopen("prowess.txt", "w"). - Check if the file opened successfully (
fptr != NULL). - Read a string from the user.
- Loop through the string and use
putc(text[i], fptr)to write each character to the file. - 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
ibefore using it in theforloop. - Forgetting to close the file with
fclose(fptr)at the end of the program, which can cause data to not be saved properly.