Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - putc and fputc

Node:putc and fputc, Next:, Previous:getc and fgetc, Up:Single-character input and output



putc and fputc

If you want to write a single character to a stream other than stdout, you can use the putc function. This function is very similar to putchar, but accepts an argument that specifies the stream to which to write. It takes a single integer parameter containing a character (the argument can be a single-quoted text character, as in the example below), and sends the character to the specified stream. If a write error occurs, putc returns EOF; otherwise, it returns the integer it was passed. This can simply be disregarded, as in the example below.

The following code example creates a text file called snazzyjazz.txt. It then writes an X, a space, and then a line of ten exclamation marks (!!!!!!!!!!) to the file, and a newline character to it using the putc function. Notice the use of the for loop; by this means, putchar can be used not just for one character, but multiple times. , then writes ten exclamation mark characters (!!!!!!!!!!)

#include <stdio.h>

int main()
{
  int i;
  FILE *my_stream;
  char my_filename[] = "snazzyjazz.txt";

  my_stream = fopen (my_filename, "w");

  putc ('X', my_stream);
  putc (' ', my_stream);
  for (i=1; i<=10; i++)
    {
      putc ('!', my_stream);
    }
  putc ('\n', my_stream);

  /* Close stream; skip error-checking for brevity of example */
  fclose (my_stream);

  return 0;
}

There is another function in the GNU C Library called fputc. It is identical to putc in most respects, except that putc is usually implemented as a macro function and is highly optimised, so is preferable in most situations.

 
 
  Published under free license. Design by Interspire