C (programming language)
C Program to Create a File and Write Data in it using fputs() and fputc() functions
C Program to Create a File and Write Data in it using fputs() and fputc() Functions
Introduction
This guide will demonstrate how to create a C program that effectively generates a new file and writes data into it. We’ll utilize two essential file I/O functions, fputs()
and fputc()
, to achieve this task, exploring their distinct capabilities and proper usage.
Key Concepts
- File Handling in C: C provides functions like
fopen()
,fputs()
,fputc()
, andfclose()
to handle file operations. - fputs() Function: Writes a string to a file, including the null terminator.
- fputc() Function: Writes a single character to a file.
Steps to Implement
- Include Necessary Header:
C
#include <stdio.h>
- Declare Variables:
C
FILE *fp;
char filename[50];
char data[100];
char ch;
- Get File Name and Data from User:
C
printf("Enter the filename to create: ");
fgets(filename, sizeof(filename), stdin);
filename[strcspn(filename, "\n")] = '\0'; // Remove newline from filename
printf("Enter the data to write: ");
fgets(data, sizeof(data), stdin);
- Open the File in Write Mode:
C
fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error creating file!\n");
return 1;
}
- Write Data Using fputs():
C
fputs(data, fp);
- Write Additional Character Using fputc():
C
ch = '!';
fputc(ch, fp); // Write a single character
- Close the File:
C
fclose(fp);
- Indicate Success:
C
printf("Data written to file successfully!\n");
Complete Example Code:
C
#include <stdio.h>
int main() {
FILE *fp;
char filename[50];
char data[100];
char ch;
printf("Enter the filename to create: ");
fgets(filename, sizeof(filename), stdin);
filename[strcspn(filename, "\n")] = '\0';
printf("Enter the data to write: ");
fgets(data, sizeof(data), stdin);
fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error creating file!\n");
return 1;
}
fputs(data, fp);
ch = '!';
fputc(ch, fp);
fclose(fp);
printf("Data written to file successfully!\n");
return 0;
}
Key Points to Remember
fputs()
writes a string, including the null terminator, to the file.fputc()
writes a single character to the file.- Always check for file opening errors using
if (fp == NULL)
. - Close the file using
fclose()
when finished to release resources. - Use
"w"
mode for writing to a new file or overwriting an existing one. - Use
"a"
mode for appending to an existing file.