Showing posts with label C programming language. Show all posts
Showing posts with label C programming language. Show all posts

#pragma directive in C

 This directive provides some additional information to the compiler and it is also used to turn on or off certain special features.  For example, #pragma startup and #pragma exit were used to call specific functions during program entry (before main()) and exit(after main()) correspondingly.



Example C program to illustrate #pragma startup and #pragma exit:

  #include <stdio.h>
  void in() {
        printf("#pragma start in\n");
        printf("Inside in\n");
  }

  void out(){
        printf("#pragma exit out\n");
        printf("Inside out()\n");
  }

  #pragma startup in
  #pragma exit out

  int main() {
        printf("I am inside main function\n");
        printf("Going out of main()\n");
        return 0;
  }

  Output:
  #pragma start in
  Inside in
  I am inside main function
  Going out of main()
  #pragma exit out
  Inside out()


#pragma warn directive can be used to suppress specific warning as follows.
#pragma warn -rvl:
          suppresses warnings related to return values
#pragma warn -par:
          suppresses warnings related to parameters like unused parameters.
#pragma warn -rch:
          suppress warning related to unreachable codes.


Example C program to illustrate #pragma warn:

  #include <stdio.h>
  #pragma warn -rvl
  #pragma warn -par
  #pragma warn -rch

  int retval() {
        printf("missing to return value\n");
  }

  int unused_para(int a) {
        printf("I m not using my parameter value\n");
        return 0;
  }

  int unreachable_code() {
        printf("have some code after return statment\n");
        return 0;
        printf("Code after return statement\n");
        printf("Unreachable code\n");
  }

  int main() {
        retval();
        unused_para(8);
        unreachable_code();
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc pragmawarn.c
  jp@jp-VirtualBox:~/cpgms/$ ./a.out
  missing to return value
  I m not using my parameter value
  have some code after return statment

If we check the above output, there won't be any warning messages.  This is due to the usage of #pragma warn.  If we remove those three pragma directives in our program, we will get warnings for unreachable code, unused parameters etc.

#ifdef, #ifndef and #endif directives in C

 #ifdef

If the named macro is defined, then the code between #ifdef and #endif will be compiled.

#ifndef
If the named macro is not defined, then the code between #ifndef and #endif will be compiled.


#ifdef, #ifndef and #endif example in C
 
  #include <stdio.h>
  #define NAME "Raj"

  int main() {

        #ifdef NAME
                printf("#ifdef: Value of NAME is %s\n", NAME);
        #endif

        #ifndef VAL
                printf("#ifndef: macro VAL is not defined\n");
        #endif
        return 0;
  }


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  #ifdef: Value of NAME is Raj
  #ifndef: macro VAL is not defined


In the above program, macro NAME is defined.  So, the code between #ifdef and #endif is executed. Similarly, the code between #ifndef and #endif is executed as the macro VAL is not defined.

#if, #elif, #else and #endif example

 #if

If the resultant value of the arithmetic expression is non-zero, then the code between #if and #endif will be compiled.

Example:
#if 10 > 5
     printf("10 is greater than 5");
#endif

The code between #if and #endif will be compiled since the resultant value of the expression(10 > 5) is non-zero.


#elif
This provides an alternate expression to evaluate

Example:
#if 10 < 5
     printf("10 is less than 5");
#elif 10 > 5
     printf("10 is greater than 5");
#endif

The expression at #if directive evaluates to 0.  So, the expression at #elif is evaluated. If it is non-zero, then the code between #elif and #endif will be compiled.


#else
If the resultant value of the arithmetic expression is false for #if, #ifdef or #ifndef, then the code between #else and #endif will be compiled.

Example:
#if 10 < 5
     printf("10 is less than 5");
#else
     printf("10 is greater than 5");
#endif


#endif
This acts as an end directive for #if, #ifdef, #ifndef, #elif or #if

#if 100 < 50   // resultant value of expression is 0
   printf("#if directive");
#elif 50 < 10  // resultant value of the expression is 0
    printf("#elif directive");
#else
    printf("#else directive");  // this statement would be executed
#endif

Example C program to illustrate #if #elif #else #endif usage in C:

  #include <stdio.h>
  #define VAL1 10
  #define VAL2 20
  #define VAL3 30

  int main() {
    #if VAL1 > VAL2
          printf("%d is greater than %d\n", VAL1, VAL2);
    #elif VAL1 > VAL3
          printf("%d is greater than %d\n", VAL1, VAL3);
    #else
          printf("%d is less than %d and %d\n", VAL1, VAL2, VAL3);
    #endif
    return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  10 is less than 20 and 30

#define vs const

 Earlier, #define is the only way to define constants.  Later const came in, which is also used to define constants.  Most of the programmers prefer to use const over #define for the following reasons

  1. Syntax check will be done for const but not for #define. The #define directive is not checked for syntax errors until the error macro is used in code block.
  2. #define can only define simple constant.  But, const can define complex constants as shown below.
struct student {
         char name[100];
         int age;
         float percentage;
};

const struct student obj = {"Victor", 20, 89};

Consider the following example,

  #include <stdio.h>
  #define SUM 10+
  int main() {
        int a;
        printf("Hello world\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Hello world


In the above C program, we have a syntax error in macro definition(#define SUM 10+). But, it wasn't reported to us since we haven't used it anywhere in our code.  Let us see what happen if we use the same macro inside the code block

  #include <stdio.h>
  #define SUM 10+
  int main() {
        int a = SUM;  // SUM is the macro with syntax error
        printf("Hello world\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc pgm.c 
  pgm.c: In function ‘main’:
  pgm.c:4: error: expected expression before ‘;’ token


In the above program, the definition for macro SUM has syntax error and the same is assigned to integer variable a.  During preprocessing 10+ would be assigned to variable a, compiler detects the same as error during compilation process.

Let us see how const behaves when there is some syntax error.


  #include <stdio.h>
  int main() {
        const int a = 10+; 
        printf("Hello world\n");
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc pgm.c 
  pgm.c: In function ‘main’:
  pgm.c:4: error: expected expression before ‘;’ token


Syntax error with const is reported during compilation itself.

#undef directive in C

 #undef directive is used to undefine a macro that has been defined earlier using #define. It is used if any macro is not needed or if the macro needs to redefined.


Example:
     #undef SAMPLE

The above statement would remove the definition for the macro named SAMPLE.

#undef directive example in C

  #include <stdio.h>
  #define NUM 10

  int main() {
        int a = NUM;
        printf("Value of a: %d\n", a);
        #undef NUM   // undefining macro NUM
        #ifdef NUM
             printf("NUM macro defined\n");  // this part is ignored as NUM is undefined
        #else
             printf("Undefine macro NUM\n");
        #endif
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/cpgms/preprocessor$ ./a.out
  Value of a: 10
  Undefine macro NUM

#define directive in C

 #define directive is used to create definition for a macro.  Below is the general form of macro


#define <MACRO_NAME>  <MACRO_VALUE>

Usually, macro names are written in upper case characters.  During preprocessing, the macro names in program would be replaced by value of the macro.

Consider the following example,
char first_name[20];
char last_name[20];
char course[20];
char school[20];

Above are the declaration for four different character arrays, each can hold 20 characters. Suppose, if user wants to change the size of all character array from 20 to 30, then user has to modify array index of all the above character arrays.  Sometimes, we may miss to update in all the places would create problem in our code.  In order to avoid this short coming, we use macros.

#define SIZE 20  // SIZE - macro name and 20 is its value
char first_name[SIZE];
char last_name[SIZE];
char course[SIZE];
char school[SIZE];

Now, if user wants to change the array size to 30, then he needs to change the value of macro (SIZE) alone as shown below.

#define SIZE 30             // changed the value of macro
char first_name[SIZE];
char last_name[SIZE];
char course[SIZE];
char school[SIZE];

Now, the size of all the above arrays has been increased to 30.


#define directive C example:

  #include <stdio.h>
  #include <string.h>
  #define SIZE 20

  int main() {
        char first_name[SIZE], last_name[SIZE];
        char course[SIZE], school[SIZE];
        strcpy(first_name, "Will");
        strcpy(last_name, " Smith");
        strcpy(course, "7th Grade");
        strcpy(school, "Vidya vikas");
        printf("Name: %s%s\n", first_name, last_name);
        printf("Course: %s\n", course);
        printf("School: %s\n", school);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc define.c
  jp@jp-VirtualBox:~/$ ./a.out
  Name: Will Smith
  Course: 7th Grade
  School: Vidya vikas


If user wants to change the size of all array variables to 30(elements), then its enough to change the value of macro SIZE alone.

Parametrized macros in C

 Macros with arguments are called parametrized macros.  Consider the following example,


#define AREA(r) (3.14 * r * r)

Here, AREA is a macro with parameter 'r'.  Macro AREA(r) would be expanded as 3.14 * r * r during preprocessing.


Parameterized macros example in C

  #include <stdio.h>
  #define AREA(r) (3.14 * r * r)
  #define GREATER(x,y) (x > y? x:y)
  #define ISDIGIT(x) (x >= 48 && x <=57)

  int main() {
        int a, b, ch;
        printf("1. Calculate area of circle\n");
        printf("2. Greatest of two numbers\n");
        printf("3. Given i/p is digit or not\n");
        printf("Enter the operation you wanna perform:");
        scanf("%d", &ch);

        switch(ch) {
                case 1:
                        printf("Enter radius:");
                        scanf("%d", &a);
                        printf("Area of circle:%d\n", (int)AREA(a));
                        break;
                case 2:
                        printf("Enter two nos:");
                        scanf("%d%d", &a, &b);
                        printf("Greatest: %d\n", GREATER(a, b));
                        break;
                case 3:
                        printf("Enter a value:");
                        scanf("%d", &a);
                        printf("Digit: %s\n", ISDIGIT(a)?"YES":"NO");
                        break;
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc paramacro.c
  jp@jp-VirtualBox:~/$ ./a.out
  1. Calculate area of circle
  2. Greatest of two numbers
  3. Given i/p is digit or not
  Enter the operation you wanna perform:3
  Enter a value:5
  Digit: NO

Conditional compilation in C language

 Conditional compilation is a compiling method which helps to generate different source code or executable based on the conditions provided to the preprocessor directives(#ifdef, #ifndef, #else).  Basically, preprocessor would check the truth value of the conditional and modify the source code based on the result. Suppose, if the resultant value of the conditional is zero, then the code block owned by the evaluated conditional would be removed during preprocessing.


Consider the following example,

   #define CLIENT 1
   #define NUM1 10
   #define NUM2 20
   int main() {
        int a = NUM1, b = NUM2;
        #ifdef CLIENT
             printf("Client1's Addition O/P: %d\n", a + b);
        #else
             printf("Client2's Addition O/P: %d\n", a + b);
        #endif
        return 0;
   }

Here, the macro CLIENT has been defined and its values is 1.  So, the statements present between #ifdef and #else will remain after preprocessing.  Whereas, the code present between #else and #endif would be removed during preprocessing.  Below is the preprocessed code for the above program.

   # 1 "condcompile.c"
   # 1 ""
   # 1 ""
   # 1 "condcompile.c"

   int main() {
        int a = 10, b = 20;
        printf("Client1's Addition O/P: %d\n", a + b);
        return 0;
   }

From the above output, we could see that the following statement has been removed from code since #else evaluates to 0.
   printf("Client2's Addition O/P: %d\n", a + b);


Let us see another example for better understanding.
    #define CLIENT 1
    #define NUM1 10
    #define NUM2 20
    int main() {
           int a = NUM1, b = NUM2;
      #ifndef CLIENT
           printf("Client1's Addition O/P: %d\n", a + b);
      #else
           printf("Client2's Addition O/P: %d\n", a + b);
      #endif
           return 0;
   }

In the above program, we have changed #ifdef to #ifndef.  #ifndef checks whether the given macro is not defined.  In our case, #ifndef CLIENT would check whether the macro named CLIENT is defined or not.  In this case, macro CLIENT is defined.   So, the code block present in-between #else and #endif would remain after preprocession.  Whereas, the code block present in-between #ifndef and #else would be removed during preprocessing.

  /* preprocessing the source code */
  jp@jp-VirtualBox:~/$ gcc -E condcompile.c
  
  /* preprocessed code */
  # 1 "condcompile.c"
  # 1 ""
  # 1 ""
  # 1 "condcompile.c"
  int main() {
         int a = 10, b = 20;
         printf("Client2's Addition O/P: %d\n", a + b);
        //Client2's code alone got compiled
       return 0;
  }

Conditional compilation example in C

  #include <stdio.h>
  #define CLIENT 1
  #define NUM1 10
  #define NUM2 20
  int main() {
        int a = NUM1, b = NUM2;
        #ifdef CLIENT
             printf("Client1's Addition O/P: %d\n", a + b);
        #else
             printf("Client2's Addition O/P: %d\n", a + b);
        #endif
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Client1's Addition O/P: 30

File inclusion in C language

 File inclusion directive is used to include the contents of standard header files or user written program files to another file.  Usually, angle braces are used to include standard library header file and double quotes are used to include user written program files.



Example:
     #include <stdio.h> => includes the contents of standard header file "stdio.h"
     #include "add.c"    => includes the contents of user written program file "add.c"


File inclusion C example:

  // add.c - user written program file
  #define SIZE 5

  int add(int a, int b) {
          return (a + b);
  }



  // fileinclusion.c
  #include <stdio.h>  // standard library header file
  #include "add.c"     // user written program file

  int main() {
        int a[SIZE], i, sum =0;
        printf("Enter any 5 nos to perform addition\n");
        for (i = 0; i < SIZE; i++) {
                scanf("%d", &a[i]);
        }
        for (i = 0; i < SIZE; i++) {
          /* calling add() - function in add.c */
                sum = add(sum, a[i]);
        }
        printf("Sum of 5 numbers: %d\n", sum);
        return 0;
  }


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter any 5 nos to perform addition
  12   23   34   45   56
  Sum of 5 numbers: 170

Macro Expansion in C

 We can use symbolic names to identify constant values or expressions.  At the time of preprocessing these symbolic names will be replaced by the constant values or expressions.  User can see the preprocessed code of any C program using the below command.


%gcc   -E   <C file_name>

Macro expansion example in C:
Consider the following C program,
  #define NAME "Khan"
  #define BIG(num1, num2) ((num1 > num2) ? num1: num2)

  int main() {
        printf("My name is %s\n", NAME);
        printf("%d is bigger\n", BIG(10, 20));
        return 0;
  }

Here, NAME and BIG are two macros.  Let us do preprocessing for the above C program and check the output for the same.

  Output:
  jp@jp-VirtualBox:~/$ gcc -E pgm.c > output.txt
  jp@jp-VirtualBox:~/$ cat output.txt 
  # 1 "pgm.c"
  # 1 "<built-in>"
  # 1 "<command-line>"
  # 1 "pgm.c"

  int main() {
        printf("My name is %s\n", "Khan");
        printf("%d is bigger\n", ((10 > 20) ? 10: 20));
        return 0;
  }


From the above output, we could see that the macros NAME and BIG are replaced by their values or expressions.  This is called macro substitution or macro expansion.

What is a Preprocessor?

 Preprocessor is nothing but a program which is executed on C source code before the compilation process.  It provides facility to handle named constant, macros and file inclusion.  And it begins with the preprocessor directive hash symbol(#).


Example:
     #define SIZE 100

Actually the source program is translated to object code on compilation.  Before the compilation process, preprocessing takes places.  During preprocessing the following operations would take place.

1.  macro substitution
2.  File inclusion
3.  Conditional compilation


Execution of an ordinary C program:
source program -> preprocessing+compilation -> object code-> linking ->executable

How to preprocess a C code?
The following program will give you a clear picture on preprocessing:
jp@jp-VirtualBox:~/cpgms/preprocessor$ cat preprocessor.c
#define SIZE 10

int main() {
    int a = SIZE;
    printf("Value of a: %d\n", a);
    return 0;
}


In the above program we have defined a macro named SIZE, whose value is 10.  Now we are going to do preprocessing alone for the above program and see the output of it.

gcc -E <program.c>

option 'E' will help us to do preprocessing alone for the C program

jp@jp-VirtualBox:~/cpgms/preprocessor$ gcc -E preprocessor.c
# 1 "preprocessor.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "preprocessor.c"


int main() {
 int a = 10;     => SIZE substituted by 10(macro substitution)
 printf("Value of a: %d\n", a);
 return 0;
}

Low level input and output functions in C - creat, open, read, write, close and lseek

 Below are the built-in functions available in C which can be used to perform low level input output operations.


open():
     Opens a file on calling it and returns file descriptor on success.  Otherwise, it returns 1.

Syntax:
     int open(const char  *path, int oflag, mode_t mode);

where path is the name of the file, oflag can be either O_RDONLY(open for read only), O_WRONLY(open for write only) and O_RDWR(open for read or write) and the third argument provides access permission information(S_IREAD, S_IWRITE, S_IEXEC etc.)


creat():
     It creates a new file on calling it and returns file descriptor on success.  Otherwise, 1 is returned.

Syntax:
     int creat(char *name, mode_t mode);

where name is the name of the file and the second argument is mode which provides access permission details(S_IREAD, S_IWRITE, S_IEXEC etc).


read():
     Data can be read from the opened file using read function.

Syntax:
     ssize_t read(int filedes, void *buf, size_t nbytes);

the above function reads nbytes of data from the file referred by file descriptor filedes and writes the read data to buffer buf.  It returns 0 if there's no other data is to read.  Otherwise, it returns the number of bytes of data read.


write():
     Data can be written to a opened file using write function.

Syntax:
     ssize_t write(int fd, const void *buf, size_t count);

 writes count bytes from the buffer buf to the file referred by file descriptor fd.


close():
     It closes a opened file. It returns 0 on success, 1 on failure.

Syntax:
     int close(int filedes);

where filedes is the file descriptor.  


lseek():
     It re-positions the file offset to perform read or write operation.

Syntax:
     off_t lseek(int fd, off_t offset, int origin);

it sets the current position in the file referred by file descriptor fd to offset, which is taken relative to the position pointed by origin.


creat, open, read, write, lseek and close example in C

  #include <stdio.h>
  #include <fcntl.h>
  #include <unistd.h>
  #include <sys/stat.h>
  int main() {
        int fd1, fd2, n;
        char str[100];

        /* open an input file in read mode */
        fd1 = open("input.txt", O_RDONLY, 0);
        /* creat an output file with read write permissions */
        fd2 = creat("output.txt", 0666);

        /* read the data from input file and write it to output file */
        while ((n = read(fd1, str, 10)) > 0) {
                write(fd2, str, n);
        }

        /* move the cursor to the 12 byte of the input file */
        lseek(fd1, 12, 0);

        /* write the given text in output file */
        write(fd2, "\nMoved cursor to 12th bytes\n", 28);

        /* writes the contents of input file from 12 byte to EOF */
        while ((n = read(fd1, str, 10)) > 0) {
                write(fd2, str, n);
        }

        /* close both input and output files */
        close(fd1);
        close(fd2);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ cat input.txt 
  hello world
  hello world
  hello world
  hello world
  jp@jp-VirtualBox:~/$ ./a.out

  jp@jp-VirtualBox:~/$
  jp@jp-VirtualBox:~/$ cat output.txt 
  hello world
  hello world
  hello world
  hello world

  Moved cursor to 12th bytes
  hello world
  hello world
  hello world

Formatted input and output functions in C

 The following are built-in functions available in C language which can be used to perform formatted input output operations.


Formatted input functions in C:
int fscanf(FILE *stream, const char *format, ...)
Performs input format conversion.  It reads the input from the stream and does format conversion.  Then, it will assign those converted values to the subsequent arguments of format correspondingly.  And it returns the number of inputs matched and got assigned with values successfully.

int scanf(const char *format, ...)
scanf() is equivalent to fscanf(stdin, ...)

int sscanf(char *str, const char *format)
sscanf() is identical to sscanf() except that the inputs are taken from the string str.


scanf fscanf sscanf example in C

  #include <stdio.h>
  int main() {
        FILE *fp;
        int i, age[3], rollno[3];
        char name[3][32], str[128] = "13:103:Ram";
        fp = fopen("input.txt", "r");

        /* input data for student 1 from user */
        printf("Enter age rollno and name for student 1:\n");
        scanf("%d%d%s", &age[0], &rollno[0], name[0]);

        printf("Reading age, rollno and name from file(input.txt)..\n");
        /* input data for student 2 from file */
        fscanf(fp, "%d%d%s", &age[1], &rollno[1], name[1]);

        printf("Reading age, rollno and name from string..\n");
        /* input data for student 3 from string */
        sscanf(str, "%d:%d:%s", &age[2], &rollno[2], name[2]);
                printf("          Age  Rollno name\n");

        /* print the result */
        for (i = 0; i < 3; i++) {
                printf("Student %d: %d    %d    %s\n",
                                i, age[i], rollno[i], name[i]);
        }
        fclose(fp);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ cat input.txt 
  10 102 Raj

  jp@jp-VirtualBox:~/$ ./a.out
  Enter age rollno and name for student 1:
  11 101 Tom
  Reading age, rollno and name from file(input.txt)..
  Reading age, rollno and name from string..
                 Age  Rollno name
  Student 0: 11    101    Tom
  Student 1: 10    102    Raj
  Student 2: 13    103    Ram




Formatted output functions in C:
int fprintf(FILE *stream, const char *format, . . .)
Performs formatted output conversion and writes the output to stream.  Return value is the number of characters printed (excludes '\0').

int printf(const char *format, . . .)
printf() is identical to fprintf(stdout, . . .)

int sprintf(char *str, const char *format, . . .)
sprintf() is similar to printf() except that the output is written into the string str.

int vfprintf(FILE *stream, const char *format, va_list arg)
vfprintf() is equivalent to fprintf() except that the variable argument is replaced by arg.

int vprintf(const char *format, va_list arg)
vprintf() is equivalent to printf() except that the variable argument is replaced by arg.

int vsprintf(char *str, const char *format, va_list  arg)
vsprintf() is equivalent to sprintf() except that the variable argument is replaced by arg.


printf fprintf sprintf example in C

  #include <stdio.h>
  int main() {
        FILE *fp;
        int rollno = 101, age = 10;
        char name[32] = "Ram", str[128];
        fp = fopen("input.txt", "w");

        /* printing rollno, age and name in stdout */
        printf("Writing output to stdout:\n");
        printf("Roll no: %d\n", rollno);
        printf("age    : %d\n", age);
        printf("Name   : %s\n", name);

        /* printing rollno, age and name in a file */
        printf("\nWriting rollno, age, name to file(input.txt)\n");
        fprintf(fp, "Roll no: %d\nage    : %d\nName   : %s\n",
                        rollno, age, name);

        /* printing rollno, age and name in a string */
        printf("Writing rollno, age, name to string(str)\n");
        sprintf(str, "Roll no: %d\nage    : %d\nName   : %s\n",
                        rollno, age, name);
        printf("\nContents in string str:\n%s\n", str);
        fclose(fp);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Writing output to stdout:
  Roll no: 101
  age    : 10
  Name   : Ram

  Writing rollno, age, name to file(input.txt)
  Writing rollno, age, name to string(str)

  Contents in string str:
  Roll no: 101
  age    : 10
  Name   : Ram

  jp@jp-VirtualBox:~/$ cat input.txt 
  Roll no: 101
  age    : 10

  Name   : Ram




vprintf vfprintf vsprintf example in C

  #include <stdio.h>
  #include <stdarg.h>
  #include

  void vformat(char *format, ...) {
        FILE *fp;
        char str[128];
        va_list arg;

        /* intializing variable argument list */
        va_start(arg, format);

        /* writing output data to stdout using vprintf */
        printf("Writing output to stdout using vprintf\n");
        vprintf(format, arg);

        /* writing data to stdout using vfprintf */
        printf("\nWriting output to stdout using vfprintf\n");
        vfprintf(stdout, format, arg);

        /* writing data to string str using vsprintf */
        printf("\nWriting output to string using vsprintf\n");
        vsprintf(str, format, arg);
        printf("Printing the contents in string str\n");
        printf("%s", str);
        va_end(arg);
  }

  int main() {
        int age = 10, rollno = 101;
        char name[32] = "Ram";
        vformat("Age: %d\nRollno: %d\nName: %s\n",
                        age, rollno, name);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Writing output to stdout using vprintf
  Age: 10
  Rollno: 101
  Name: Ram

  Writing output to stdout using vfprintf
  Age: 10
  Rollno: 101
  Name: Ram

  Writing output to string using vsprintf
  Printing the contents in string str
  Age: 10
  Rollno: 101
  Name: Ram

Character Input and Output functions in C

 The following are the built in functions available in C which can be used to to perform character input & output operations.


int fgetc(FILE *stream)
It reads the next character from the stream and returns the integer(ascii) value of the character read.

int fputc(int c, FILE *stream)
It writes the character c on the given stream.  Returns the written character on success.  Otherwise, EOF is returned.

fgetc and fputc example in C

  #include <stdio.h>
  int main() {
        int ch;
        /* prints the input data on the output screen */
        while ((ch = fgetc(stdin)) != EOF) {  //ctrl + D to exit
                fputc(ch, stdout);
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world



int getc(FILE *stream);
It reads the next character from the given stream. It evaluates the given stream more than one time, if it is a macro.  Returns integer value(ascii) of the character read.

int putc(int c, FILE *stream);
It writes the character c into the given stream.  It evaluates the given stream more than once, if it is a macro.  Returns the integer value(ascii) of the written character on success, EOF on failure.

getc and putc example in C


  #include <stdio.h>
  int main() {
        int ch;
        /* prints the input data on the output screen */
        while ((ch = getc(stdin)) != EOF) {  //ctrl + D to exit
                putc(ch, stdout);
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world



char *fgets(char *str, int n, FILE *stream)
It reads n-1 character from the input stream, stops reading if a newline character is encountered; newline + '\0' is included at the end of input string. String str is returned as the return value on success.  Otherwise, NULL is returned.


int fputs(const char *str, FILE *stream)
It writes the string str on stream.  Returns the non-negative integer on success, EOF on failure.

fgets and fputs example in C

  #include <stdio.h>
  int main() {
        char str[256];
        printf("Enter your input string:");
        fgets(str, 256, stdin);  // gets input from standard i/p
        printf("Below is your input string:\n");
        fputs(str, stdout);  // prints str in standard o/p screen
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:India is my country
  Below is your input string:
  India is my country



int getchar(void)
Inputs a character.  Returns the integer value(ascii) of the character read.

int putchar(int c)
Write character c on standard output.

getchar and putchar example in C

  #include <stdio.h>
  int main() {
        int ch;
        /* prints the input data on the output screen */
        while ((ch = getchar()) != EOF) {
                putchar(ch);
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world



char *gets(char *str)
Gets the given input string into the character array str.  Returns str on success, EOF or NULL is returned on failure.

int puts(const char *str)
It writes the given string and a newline to stdout.  Returns non-negative integer on success, EOF is returned on failure.

gets and puts example in C

  #include <stdio.h>
  int main() {
        char str[256];
        printf("Enter your input string:");
        gets(str);  // gets input from standard i/p
        printf("Below is your input string:\n");
        puts(str);  // prints str in standard o/p screen
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Hello world
  Below is your input string:
  Hello world



int ungetc(int c, FILE *stream)
It pushes character c back onto the given stream.  Returns character c on success, EOF on failure.

ungetc example in C

  #include <stdio.h>
  int main() {
        char ch;
        while ((ch = getchar()) != EOF) {  // ctrl + d is EOF
                if (ch == '\n') {
                        /*
                         * pushes # to stdin.. So, getchar()
                         * would read the character '#' on its
                         * subsequent call
                         */
                        ungetc('#', stdin);
                        continue;
                }
                putchar(ch);
        }
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  india             
  india#