Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
stream

What is putc in C?

Maham Ghazanfar

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.

The putc function in C writes a character to any output stream and returns an integer value. It is a standard function in C and can be used by including the <stdio.h> header file.

Prototype

int putc(int ch, FILE *stream)

Parameters and return value

Parameters

  • int: The integer representation of the character to be written to the output stream.

  • stream: A file stream or standard output stream identified by a pointer to the FILE object.

Return value

  • int: Integer casting of the character written by putc.

If the write operation is unsuccessful due to an error or the end of a file is reached, EOF is returned.

Code

#include <stdio.h>
int main() {
char c;
int ret;
c = 'g';
ret = putc(c, stdout); //ret stores the integer representation of the character
return 0;
}
Write to standout output with function

In the above code, the value g stored in the character variable c is displayed on standard output by the putc function and the corresponding integer value 103 is stored in the variable ret.

#include <stdio.h>
int main() {
char c;
FILE *fp = fopen("new.txt","w");
c = 'A';
putc(c, fp);
fclose(fp);
//to test whether putc was successful
FILE *fp2 = fopen("new.txt","r");
printf("%c", getc(fp));
return 0;
}
Write to file stream with function

In this example, the text file new.txt opens in write mode and is assigned to a file pointer fp. The content of variable c i.e., A, is written at the position pointed to fp in the file using the putc function.

To test whether the write was successful to the file, it should be opened in read mode, and a character read using the getc function. The character read is then displayed on standard output.

RELATED TAGS

c
stream

CONTRIBUTOR

Maham Ghazanfar
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