In C, a file can be created using the fopen() function. The file is opened in "wt" (write text) mode, which creates a new text file. If the file already exists, its previous contents are erased. The fprintf() function is then used to write text into the file.
How It Works?
stdio.h header file for file handling functions.FILE *fp.fopen("any.txt", "wt").fprintf() function.fclose() after writing the data.any.txt file.#include <stdio.h> main() { FILE *fp; clrscr(); fp = fopen("any.txt", "wt"); fprintf(fp, "hello india"); fprintf(fp, "\n form of Program"); fclose(fp); getch(); }
The file any.txt will be created with the following contents:
fopen() and write data into it using fprintf()."wt" mode, use multiple fprintf() statements to write the data, and close the file using fclose().
#include <stdio.h> #include <conio.h> main() { FILE *fp; clrscr(); fp = fopen("student.txt", "wt"); fprintf(fp, "Name : Rahul"); fprintf(fp, "\nCourse : BCS"); fprintf(fp, "\nCity : Pune"); fclose(fp); getch(); }
The file student.txt will contain:
student.txt using fopen() in write mode ("wt"). The fprintf() function writes the student's details into the file line by line. Finally, fclose() closes the file and saves the data successfully.