From WikiChip
Difference between revisions of "c/basic i/o"
< c

m (fixed typo)
(fgets/getchar/scanf/)
Line 120: Line 120:
  
 
<source lang="C">printf("%s", user_input);</source>
 
<source lang="C">printf("%s", user_input);</source>
 +
 +
== fgets() - file get string ==
 +
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. The fgets() function will read at most one less than the size specified or 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:
 +
 +
<source lang="C">
 +
#include <stdio.h>
 +
int main()
 +
{
 +
    char string[100];
 +
    printf("Please enter your name: ");
 +
    fgets(string, sizeof string, stdin);
 +
    printf("Hi %s", string);
 +
    return 0;
 +
}
 +
</source>
 +
 +
The example above will prompt the user for a name. It will then store the name in <code>string</code>. Finally the string will be printed to the string. Note that we've passed <code>stdin</code> to tell fgets() it should be reading from the standard input stream.
 +
 +
== getchar() - get character ==
 +
The '''getchar()''' function performs the opposite of the putchar(). It reads a single character from the standard input stream or EOF if the end-of-file was reached.
 +
 +
<source lang="C">
 +
#include <stdio.h>
 +
int main()
 +
{
 +
    printf("Enter a character: ");
 +
    printf("You entered: %c\n", getchar());
 +
    return 0;
 +
}
 +
</source>
 +
 +
The over-simplistic example above will prompt the user for a single character and then print it back. Note that the example above does not take care of EOF values.
 +
 +
== scanf() - scan formatted input ==
 +
The '''scanf()''' function performs a task very simple that of the printf() function just backwards. The data now comes from the standard input stream and scanf() reads it and populates pointers to storage spaces of specific types specified using format specifiers. The most common format specifiers are the same as the printf(): %s, %c, and %d. For example, we can read two comma-separated int values using the code below:
 +
 +
<source lang="C">
 +
#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;
 +
}
 +
</source>
 +
 +
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 and store them at the space pointed by the arguments (<code>&a</code> means to take the address of a; this concept is explained in more depth in the [[pointers - C|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
 +
 +
  
 
[[Category:C programming language]]
 
[[Category:C programming language]]
 
[[Category:File i/o - C]]
 
[[Category:File i/o - C]]

Revision as of 04:45, 27 December 2013

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 a in-depth overview of I/O see the File I/O guide.

Standard streams

Main article: standard streams

In this article we will cover the basic idea of input and out using the basic standard streams. Standard streams are a set of preconfigured input and output channels that are automatically available to all C programs. All a program needs to do to access these streams as well as a set of functions to work with them is to include the <stdio.h> header.

#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

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 to the string. Below is a simple usage example:

#include <stdio.h>
int main()
{
    puts("This string will be printed!");
    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 printing numbers, adding padding and so forth.

putchar() - put character

Just like puts(), the putchar() function is designed to allow a program 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

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

#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:

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

Executing the code above should output:

x = 123, y = 456

The string we passed printf() was "x = %d, y = %d\n". It contains two format specifiers; both are %d, which tells printf 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 in their appropriate position in the string.

We can mix the type of arguments together. All that needs to be ensured is that the format specifiers, in order, match the types of arguments that have been passed. For example,

#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;
}

Which produce the following output:

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

In the example above the first argument which is a char is substituted where the %c format specifier is used. The second argument, which is an int is substituted where the second format specifier, %d is used. The third argument is of type const char * is substituted where the third format specifier, %s, is used. Likewise, the final argument is an int. It gets substituted where the %d format specifier is used.

The printf() function supports many different types of formats that is 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 for specifiers are possible, for example,

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

will produce

AA:BB:CC

In some rare cases, you might need to print an actual percent symbol. The printf() function supports the %% format specifier which produces the % character. For example:

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

Will produce

99%

printf() Safety

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

printf("%s", user_input);

fgets() - file get string

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. The fgets() function will read at most one less than the size specified or 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:

#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 string. Finally the string will be printed to the string. Note that we've passed stdin to tell fgets() it should be reading from the standard input stream.

getchar() - get character

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

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

The over-simplistic example above will prompt the user for a single character and then print it back. Note that the example above does not take care of EOF values.

scanf() - scan formatted input

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

#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 and store them at the space pointed by the arguments (&a means to take the address of a; this concept is explained in more 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