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
- Include Necessary Header:
C
#include <stdio.h>
- Declare Variables:
C
char name[50];
int age;
FILE *fp;
- Get Data from User:
C
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Safer than gets()
printf("Enter your age: ");
scanf("%d", &age);
- Open the File for Writing:
C
fp = fopen("user_data.txt", "w"); // Open in write mode
- Check for File Opening Errors:
C
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
- Write Data to the File:
C
fprintf(fp, "Name: %s", name);
fprintf(fp, "Age: %d\n", age);
- Close the File:
C
fclose(fp);
- 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.