From WikiChip
Basic I/O - C
< c
Revision as of 06:13, 4 January 2015 by Inject (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

One of the most universal things that all programs need is a way to process some input and output the produced results. I/O stands for Input and Output. Input is the data that is sent into the program; output is the data that is sent out of the program. This article covers the basic I/O facilities that the C programming language provides. This article will only present the simplest forms of I/O operations. For an in-depth overview of I/O, see the File I/O guide.

Standard streams[edit]

Main article: standard streams

In this article, we will cover the basic idea of input and output using the basic standard streams. Standard streams are a set of pre-configured input and output channels, which are automatically available to all C programs. To access these streams, as well as a set of functions to work with them, the only necessary step is to include the <stdio.h> header file into your program's C source-code.

Example

#include <stdio.h>

The three standard streams that are available are the: standard input stream, standard output stream, and the standard error stream. They are represented in C as the stdin, stdout, and stderr objects respectably. The standard input stream is used to read data that is sent to the program. Typically such data can come from the keyboard or from a file that has been redirected to the program. The standard output stream typically represents the screen. The standard error stream, as the name implies, is used by the program to output various diagnostic messages that it encounters.

puts() - put string[edit]

puts() is a very simple function that outputs a string to the standard output stream. One thing to note about the puts() function is that it appends a new-line character (\n) to the string. Below is a simple usage example:

#include <stdio.h>
int main()
{
    puts("This string will be printed, along with a newline character!");
    return 0;
}

While the puts() function is great for printing strings, its capabilities end there. A more flexible function is required to perform something more complex, such as cases where you want to print numbers, add padding, and so forth.

putchar() - put character[edit]

Just like puts(), the putchar() function is designed to allow a program to print a single character onto the standard output stream. The program below prints "Hello" followed by the newline character.

#include <stdio.h>
int main()
{
    /* print "Hello" */
    putchar('H'); putchar('e'); putchar('l'); putchar('l'); putchar('o');
    putchar('\n'); /* print a newline character */
    return 0;
}

printf() - print formatted string[edit]

The printf() function is, perhaps, the most complex function we will talk about in this article. The printf() function receives a string with special characters in it, which are known as format specifiers, along with normal text. The special characters, which are always prefixed by the % character, tell the printf() function what the next argument is about and what formatting to apply. The printf() function can also be used without any format specifiers.

Example - No format specifiers

#include <stdio.h>
int main()
{
    printf("Hello, World!\n");
    return 0;
}

Will print the string "Hello, World!\n". printf()'s power comes from it format specifiers. In this article we will cover the most basic format specifiers: %s, %c, and %d which are used for strings, characters, and integers respectably. The example below prints the content of a variable of type int:

Example This will print the content of a variable of type int:

#include <stdio.h>
int main()
{
    int x = 123, y = 456;
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

Executed Output Result:

x = 123, y = 456

The string we passed to printf() was "x = %d, y = %d\n", which contains two format specifiers; both are %d, which tells printf() that the next two arguments are of type int. The printf() function reads the two arguments, interprets them as int type and prints their value to the standard output stream, while maintaining their appropriate positions in the string.

We can mix the different types of arguments together. The only thing that needs to be ensured is that the format specifiers, in order, match the types of arguments that have been passed.

Example - Shows how we ensure the order of format specifiers respective to their arguments:

#include <stdio.h>
int main()
{
    int x = 123, y = 456;
    const char *str = "Some text!";
    char z = 'A';

    printf("z=%c; x=%d; str='%s'; y=%d;\n", z, x, str, y);
    return 0;
}

Executed Output Result:

z=A; x=123; str='Some text!'; y=456;
Printf format specifiers.svg

The above is a great example which reflects how the first argument, which is a char, is substituted where the %c format specifier is used. The second argument, which is an int, is then substituted where the second format specifier, %d, has been used. The third argument, which is of type const char *, is substituted where the third format specifier, %s, has been placed. Likewise, the final argument is an int type; it gets substituted where the %d format specifier is used.

The printf() function supports many different types of formats that are not discussed here. The main thing to remember is that the values being passed to printf() must agree with the format specifiers used in the string. Any combination is possible with the format specifiers.

Example - Showing off the different format specifier combinations:

#include <stdio.h>
int main()
{
    printf("%s:%s:%s\n", "AA", "BB", "CC");
    return 0;
}

Executed Output Result:

AA:BB:CC

There are rare instances where you might need to print an actual percent symbol. The printf() function supports the %% format specifier, which produces the % character.

Example - How to print an actual percentage symbol:

#include <stdio.h>
int main()
{
    printf("%d%%\n", 99);
    return 0;
}

Executed Output Result:

99%

printf() Safety[edit]

Because the printf() function interprets the first argument as the format string, extra precautions must be taken to ensure that no arbitrary user input is accidentally passed as the first argument of printf(). If the user input contains text with special format specifiers, and is passed as the first argument to printf(), the results could be catastrophic! To avoid these types of errors completely, never pass arbitrary strings as the format string to printf().

printf("%s", user_input);

fgets()[edit]

The fgets() function can be used to read a string of certain length from a stream. The fgets() function takes a pointer to a char, which is used to store the string that will be read, the size of that string, and the stream itself. The fgets() function will read, at most, either: one less than the size specified; up to the next newline character; or end-of-file. For example, we can read a string from the user and print it with the following example:

Example - Read a string from user and print it to the output stream:

#include <stdio.h>
int main()
{
    char string[100];
    printf("Please enter your name: ");
    fgets(string, sizeof string, stdin);
    printf("Hi %s", string);
    return 0;
}

The example above will prompt the user for a name; it will then store the name in a string type. Finally, the string will be printed to the output stream. Note that we have passed stdin to tell fgets() that it should be reading from the standard input stream.

getchar() - get character[edit]

The getchar() function performs in opposite of the putchar() function. getchar() reads a single character from the standard input stream, or EOF if the end-of-file was reached.

Example - Prompt user to enter a single character and then print to the output stream:

#include <stdio.h>
int main()
{
    printf("Enter a character: ");
    printf("You entered: %c\n", getchar());
    return 0;
}

Note that the example above does not take care of EOF values.

scanf()[edit]

The scanf() function performs a task very similar to that of the printf() function, just backwards. The data in scanf(), in difference to printf(), now comes from the standard input stream; scanf() reads it and populates pointers to storage spaces, of specific types specified, using format specifiers. The most common format specifiers for scanf() are the same as the printf() specifiers: %s, %c, and %d. For example, we can read two comma-separated int values using the code below:

Example - Read two comma-separated int values from user input:

#include <stdio.h>
int main()
{
    int a, b;
    printf("Please enter two integers separated by a single comma: ");
    scanf("%d,%d", &a, &b);
    printf("%d + %d = %d\n", a, b, a + b);
    return 0;
}

The code above will request the user for two integers. The scanf() function will attempt to scan and parse two integers separated by a comma, then store the integers at the space pointed to by the arguments (&a means to take the address of a; this concept is explained more in-depth in the pointers guide). A sample output of the program above might look like this:

Please enter two integers separated by a single comma: 1793,430
1793 + 430 = 2223

We mentioned earlier that the scanf() function can also read strings via the %s format specifier. While no size is required, to prevent buffer overflow, it is crucial to provide the size (which must be one less than the buffer size as to allow for a null terminator) of the string.

Example - Read user input string, while specifying the expected size to reduce the chances of buffer overflow:

#include <stdio.h>
int main()
{
    char name[20];
    printf("Please enter your name: ");
    scanf("%19s", name);
    printf("Welcome back %s!\n", name);
    return 0;
}

You will notice that, in the example above, scanf() will attempt to store the string (which has been specified to occupy up to 19 characters, plus one more for the null terminator) in the region it has been pointed to by the name.

Executed Output Example:

Please enter your name: david
Welcome back david!