[c]working with files

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
		printf("Error with file.\n");
	fprintf(fout,"%s",line); //copy the input data into the file.
	fclose(fout); //save and close.
	return 0;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s