w3resource

C fputc() function

C library function - fputc()

The fputc() function is used to write the byte specified by c to the output stream pointed to by stream, at the position indicated by the associated file-position indicator for the stream (if defined), and shall advance the indicator appropriately.

Syntax:

int fputc(int c, FILE *stream)

Parameters:

Name Description Required /Optional
c This is the character to be written. This is passed as its int promotion. Required
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required

Return value

  • Upon successful completion, fputc() shall return the value it has written.
  • Otherwise, it shall return EOF, the error indicator for the stream shall be set, and errno shall be set to indicate the error.

Example: fputc() function

#include <stdio.h>
int main () {
   FILE *fp;
   int ch;
   char string[100];
   
   fp = fopen("test.txt", "w+");
   for( ch = 65 ; ch <= 122; ch++ ) {
      fputc(ch, fp);
   }
   fclose(fp);
   fp=fopen("test.txt","r");
   fgets(string,100,fp);
   printf("The string is:\n%s",string);
   fclose(fp); 
   return 0;
}

Output:

The string is:
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz

Example: Write the contents of buffer to a file

#include <stdio.h>
 
#define ALPHA  6
 
int main(void)
{
  FILE * fp;
  int i;
  int ch;
  char string[6];
 
  char buffer[ALPHA + 1] = "aeiou";
 
  if (( fp = fopen("test.txt", "w"))!= NULL )
  {
    /* Put buffer into file */
    for ( i = 0; ( i < sizeof(buffer) ) &&
           ((ch = fputc( buffer[i], fp)) != EOF ); ++i );
    fclose(fp);
  }
  else
   perror( "Error opening test.txt" );
   fp=fopen("test.txt","r");
   fgets(string,6,fp);
   printf("The string is: %s",string);
   fclose(fp); 
   return 0;
}

Output:

The string is: aeiou

C Programming Code Editor:

Previous C Programming: C fgets()
Next C Programming: C fputs()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

Ref : https://bit.ly/3pdEk6f