C Program to Write a String into a File

File handling in C allows you to create, write, read, and manage data files. In this tutorial, you will learn how to write a string to a file using C programming.


Objective

  • Accept a string from the user.
  • Write the string into a file using file handling functions.
  • Understand how to work with file pointers in C.

Example C Program

#include <stdio.h>

int main() {
FILE *fp;
char str[100];

// Open file in write mode
fp = fopen("output.txt", "w");

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

// Get input from user
printf("Enter a string to write into the file: ");
fgets(str, sizeof(str), stdin);

// Write string to file
fprintf(fp, "%s", str);

// Close the file
fclose(fp);

printf("String written to file successfully.\n");

return 0;
}

Sample Output

Enter a string to write into the file: Hello, File Handling in C!
String written to file successfully.

Content of output.txt:

Hello, File Handling in C!

Explanation

  • FILE *fp; declares a file pointer.
  • fopen("output.txt", "w") opens the file in write mode.
  • fgets() reads a line of text from the user.
  • fprintf() writes the string to the file.
  • fclose(fp) closes the file to save data properly.

Key Concepts Covered

  • File handling (fopen, fprintf, fclose)
  • Writing strings to files
  • Using fgets for safer input

Key Takeaways

  • File operations in C require proper error checking.
  • Always close the file using fclose() to prevent data loss.
  • Use "w" mode to overwrite the file or "a" mode to append data.

Conclusion

Writing to a file is an essential skill in C programming. It allows you to save data permanently and is widely used in applications such as logging, reports, and data persistence. Start with writing strings and gradually learn to handle complex file operations like reading, appending, and updating.

Previous Article

C Program for Sorting an Array Using Pointers

Next Article

Introduction to Pointers in C: Call by Value vs Call by Reference

Write a Comment

Leave a Comment

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

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨