codegurukool.com · Free coding tutorials & online compiler

Home › C Tutorial › C create and write files

C create and write files

Save text to a file.

fopen(name, "w") creates or overwrites. Use "a" to append. Write with fprintf and always fclose.

Example code

#include <stdio.h>
int main() {
  FILE *f = fopen("data.txt", "w");
  if (f == NULL) { printf("Error\n"); return 1; }
  fprintf(f, "Hello file\n");
  fclose(f);
  printf("Saved\n");
  return 0;
}

Run this code in the online editor

← C function pointersC read files →