C (programming language)

C program to get data from user and store it into the file

Introduction

This guide will demonstrate how to create a C program that effectively collects user input and saves it to a file. We’ll leverage essential file I/O functions to achieve this task, ensuring proper handling of data and resources.

Key Requirements

  • Understanding of basic C programming concepts.
  • Familiarity with file I/O operations in C.
  • A text editor or IDE for writing C code.
  • A C compiler to compile and run the code.

Steps to Implement

  1. Include Necessary Header:

C

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

C

char name[50];
int age;
FILE *fp;
  1. Get Data from User:

C

printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Safer than gets()
printf("Enter your age: ");
scanf("%d", &age);
  1. Open the File for Writing:

C

fp = fopen("user_data.txt", "w"); // Open in write mode
  1. Check for File Opening Errors:

C

if (fp == NULL) {
    printf("Error opening file!\n");
    return 1;
}
  1. Write Data to the File:

C

fprintf(fp, "Name: %s", name);
fprintf(fp, "Age: %d\n", age);
  1. Close the File:

C

fclose(fp);
  1. Indicate Success:

C

printf("Data saved successfully!\n");

Complete Example Code:

C

#include <stdio.h>

int main() {
    char name[50];
    int age;
    FILE *fp;

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);
    printf("Enter your age: ");
    scanf("%d", &age);

    fp = fopen("user_data.txt", "w");

    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    fprintf(fp, "Name: %s", name);
    fprintf(fp, "Age: %d\n", age);

    fclose(fp);

    printf("Data saved successfully!\n");

    return 0;
}

Additional Considerations

  • Use fscanf() to read formatted data from a file if needed.
  • Explore other file modes (e.g., “a” for appending) for different file operations.
  • Always handle errors gracefully to ensure program reliability.
  • Consider validating user input to prevent invalid data from being stored.

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