Thu Jun 21 2018

Write File

C Programming976 views

File Name: write-file.c

#include<stdio.h>

int main() {

	/* Declare File pointer */
	FILE *fp;
	char text[10] = "Hello!";
	int i = 0;

	/* Create/Open file 'myfile.txt' in write mode */
	fp = fopen("myfile.txt","w");

	/* Write character on file using 'fputc' function */
	while(text[i] != '\0') {
		fputc(text[i], fp);
		i++;
	}

	/* Write text on file using 'fprintf' function */
	fprintf(fp,"\nHello World!");

	/* Checking error on file */
	if (ferror(fp))
		printf("Error occur...Try Again!\n");
	else
		printf("File created and written successfully!\n");

	/* Close file */
	fclose(fp);								
	return 0;
}



/* Output */
File created and written successfully!
/* 'myfile.txt' look like */
Hello!
Hello World!
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.