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(), and fclose() 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

  1. Include Necessary Header:

C

#include <stdio.h>
  1. Declare Variables:

C

FILE *fp;
char filename[50];
char data[100];
char ch;
  1. 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);
  1. Open the File in Write Mode:

C

fp = fopen(filename, "w");

if (fp == NULL) {
    printf("Error creating file!\n");
    return 1;
}
  1. Write Data Using fputs():

C

fputs(data, fp);
  1. Write Additional Character Using fputc():

C

ch = '!';
fputc(ch, fp);  // Write a single character
  1. Close the File:

C

fclose(fp);
  1. 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.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button