C Write To Files

1. Opening a File for Writing

Use fopen() with a write mode:

FILE *fopen(const char *filename, const char *mode);
Mode Description
"w" Write (creates a new file or overwrites existing file)
"a" Append (adds data to end of file, creates file if it doesn’t exist)
"w+" Read & write (creates or overwrites file)
"a+" Read & append (creates file if doesn’t exist)

2. Writing Functions in C

Function Description
fputc(ch, fp) Writes a single character to the file
fputs(str, fp) Writes a string to the file
fprintf(fp, "format", variables) Writes formatted output (like printf)

3. Example 1: Writing a String Using fputs

#include <stdio.h>

int main() {
FILE *fp = fopen(“output.txt”, “w”); // open for writing
if (fp == NULL) {
printf(“Unable to create file!\n”);
return 1;
}

fputs(“Hello, C File Writing!\n”, fp);
fputs(“This is a second line.\n”, fp);

fclose(fp); // close the file
printf(“Data written successfully.\n”);
return 0;
}

Output in file output.txt:

Hello, C File Writing!
This is a second line.

4. Example 2: Writing a Single Character Using fputc

#include <stdio.h>

int main() {
FILE *fp = fopen(“charfile.txt”, “w”);
if (fp == NULL) {
printf(“Unable to create file!\n”);
return 1;
}

fputc(‘A’, fp); // write single character
fputc(‘\n’, fp); // newline
fputc(‘B’, fp);

fclose(fp);
return 0;
}

Output in file charfile.txt:

A
B

5. Example 3: Writing Formatted Data Using fprintf

#include <stdio.h>

int main() {
FILE *fp = fopen(“data.txt”, “w”);
if (fp == NULL) {
printf(“Unable to create file!\n”);
return 1;
}

int age = 25;
double salary = 45000.50;

fprintf(fp, “Age: %d\n”, age);
fprintf(fp, “Salary: %.2lf\n”, salary);

fclose(fp);
return 0;
}

Output in file data.txt:

Age: 25
Salary: 45000.50

6. Example 4: Appending Data to a File

#include <stdio.h>

int main() {
FILE *fp = fopen(“output.txt”, “a”); // append mode
if (fp == NULL) {
printf(“Unable to open file!\n”);
return 1;
}

fputs(“Appending this line.\n”, fp);

fclose(fp);
return 0;
}

  • The new line is added at the end without overwriting existing data.


7. Key Points About Writing to Files

  1. Use write (w) to overwrite or append (a) to add data.

  2. Always check if fopen succeeded.

  3. Close the file using fclose() after writing.

  4. Functions for writing:

    • fputc() → single character

    • fputs() → string

    • fprintf() → formatted output

  5. Appending ensures existing data is preserved.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *