🎓 A1Learner
🔍
0 of 50 lessons completed

C Write to Files

Creating a file leaves it empty. fprintf writes formatted text into it, and fputs writes a plain line.

Write one line with fprintf

One fprintf call puts "Hello, file!" into notes.txt. The screen only shows a short note; the line lives in the file.

#include <stdio.h>

int main() {
  FILE *fp = fopen("notes.txt", "w");
  if (fp == NULL) {
    printf("Could not open notes.txt.\n");
    return 1;
  }
  fprintf(fp, "Hello, file!\n");
  fclose(fp);
  printf("Wrote one line to notes.txt.\n");
  return 0;
}

Write two lines with fputs

Two fputs calls write two lines into lines.txt. The output on screen only confirms the write.

#include <stdio.h>

int main() {
  FILE *fp = fopen("lines.txt", "w");
  if (fp == NULL) {
    printf("Could not open lines.txt.\n");
    return 1;
  }
  fputs("First line.\n", fp);
  fputs("Second line.\n", fp);
  fclose(fp);
  printf("Wrote two lines to lines.txt.\n");
  return 0;
}

Write numbers with fprintf

Two fprintf calls write the scores 85 and 92 into scores.txt. The %d slots hold the numbers.

#include <stdio.h>

int main() {
  int score1 = 85;
  int score2 = 92;
  FILE *fp = fopen("scores.txt", "w");
  if (fp == NULL) {
    printf("Could not open scores.txt.\n");
    return 1;
  }
  fprintf(fp, "Score: %d\n", score1);
  fprintf(fp, "Score: %d\n", score2);
  fclose(fp);
  printf("Wrote two scores to scores.txt.\n");
  return 0;
}

Example

#include <stdio.h>

int main() {
  FILE *fp = fopen("grades.txt", "w");
  if (fp == NULL) {
    printf("Could not open grades.txt.\n");
    return 1;
  }
  fprintf(fp, "Ada: %d\n", 88);
  fprintf(fp, "Ben: %d\n", 76);
  fputs("Done.\n", fp);
  fclose(fp);
  printf("Wrote grades to grades.txt.\n");
  return 0;
}

Key points

  • fprintf writes into a file the way printf writes to the screen.
  • fprintf takes the file pointer first, then the text.
  • fputs writes one plain string into a file.
  • A \n in the text starts a new line inside the file.
  • Numbers can be written with %d and %.1f, as with printf.
  • Open the file in write mode before writing to it.
  • Close the file after writing, so the text is saved.

Two graded lines go into grades.txt with fprintf, and fputs adds a final line. The screen shows only a short note; the grades live in the file.

Note

The printed line on the screen is only a short note. The words live in the file.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which call writes formatted text into a file?