Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is fputc() in C?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

fputc() is used to write a single character to a file at the location indicated by the file pointer. After writing the character to the file, fputc() increments the file pointer by one location. Below is the declaration of the fputc() function:

int fputc (int character, FILE * stream);

The fputc() function returns the character that is written if the character is successfully written to the file. EOFEnd-of-File is returned if there is an error when writing to the file.

Parameters of the fputc() function

  • character: Character to be written.
  • stream: Pointer to the file where the character is to be written.

Code

Consider the code snippet below, which uses fputc() to write a character to a file:

#include <stdio.h>
int main() {
FILE * fPointer;
char character;
fPointer = fopen ("fputcExample.txt", "w");//opening file
fputc('a', fPointer);//writing 'a' to file
fputc('b', fPointer);//writing 'b' to file
fclose(fPointer);
return 0;
}

Explanation

The  fopen()  function is used in line 8 to open the file for writing. The fputc() function is used in line 10 to write character ‘a’ to the file location pointer with fPointer. After successfully writing the ‘a’ character to the file, fputc() increments the fPointer by one location. This way, once the next write operation is applied to the file, the data is placed after the ‘a’ character written by fputc().

Once the code above is executed, the contents of fputcExample.txt will be:

# fputcExample.txt
ab

RELATED TAGS

c

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring