Write a File in C (2 Examples)

Write a File in C (2 Examples)

  • Blog
  • 1 min read

How to write a file in C? Check the below 2 examples:

Example 1: Write a File in C Programming Language

The following C program will write a file abc.txt with a single line "Hello world.".

#include <stdio.h>
int main(){
	FILE *out=fopen("abc.txt","w");
	fputs("Hello world.",out);
	fclose(out);
	return 0;
}

Example 2:

The following C program will ask the user to input any text, and then it will write to the file.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char sentence[1000];

    // creating file pointer to write a file
    FILE *fptr;

    // open the file in write mode
    fptr = fopen("xyz.txt", "w");

    // exit 
    if (fptr == NULL) {
        printf("Error!");
        exit(1);
    }
    printf("Enter a sentence:\n");
    fgets(sentence, sizeof(sentence), stdin);
    fprintf(fptr, "%s", sentence);
    fclose(fptr);
    return 0;
}

See also: