Here’s the sample code. Objective is to open a file name – output.txt, if this file does not exist it will be created by the fopen function.
For this example the file will accept 100 characters. fprintf is to copy the contents over to output.txt.
#include <stdio.h> #include <stdlib.h> int main() { FILE *fout; char line[100]; //string char *filename = "output.txt"; printf("Enter some text."); scanf("%[^\n]s",line); //to accept multiple words fout = fopen(filename,"w"); //write mode if(filename==NULL) { printf("Error with file.\n"); exit(1); } fprintf(fout,"%s",line); //copy the input data into the file. fclose(fout); //save and close. return 0; }