m |
m |
||
(12 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
− | {{ | + | {{c title|Basic I/O}} |
− | 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 | + | 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 {{C|File I/O}} guide. |
== Standard streams == | == Standard streams == | ||
− | {{main|standard streams | + | {{main|c/standard streams|l1=standard streams}} |
− | In this article, we will cover the basic idea of input and output using the basic | + | In this article, we will cover the basic idea of input and output using the basic {{C|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 {{C|include directive|include}} the {{C|stdio.h|<stdio.h>}} header file into your program's C source-code. |
− | + | '''Example''' | |
<source lang="C">#include <stdio.h></source> | <source lang="C">#include <stdio.h></source> | ||
Line 12: | Line 12: | ||
== puts() - put string == | == 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: | + | '''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: |
<source lang="C"> | <source lang="C"> | ||
Line 18: | Line 18: | ||
int main() | int main() | ||
{ | { | ||
− | puts("This string will be printed!"); | + | puts("This string will be printed, along with a newline character!"); |
return 0; | return 0; | ||
} | } | ||
</source> | </source> | ||
− | While the <code>puts()</code> function is great for printing strings, its capabilities end there. A more flexible function is required to perform something more complex such as | + | While the <code>puts()</code> 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 == | == 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. | + | 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. |
<source lang="C"> | <source lang="C"> | ||
Line 40: | Line 40: | ||
== printf() - print formatted string == | == 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 | + | 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'' | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 53: | Line 54: | ||
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: | 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 <code>int</code>:'' | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 63: | Line 65: | ||
</source> | </source> | ||
− | + | '''Executed Output Result''': | |
x = 123, y = 456 | x = 123, y = 456 | ||
− | The string we passed printf() was <code>"x = %d, y = %d\n"</code> | + | The string we passed to '''printf()''' was <code>"x = %d, y = %d\n"</code>, which contains two format specifiers; both are <code>%d</code>, which tells '''printf()''' that the next two arguments are of type <code>int</code>. The '''printf()''' function reads the two arguments, interprets them as <code>int</code> type and prints their value to the standard output stream, while maintaining their appropriate positions in the string. |
− | We can mix the | + | 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'': | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 83: | Line 86: | ||
</source> | </source> | ||
− | + | '''Executed Output Result''': | |
z=A; x=123; str='Some text!'; y=456; | z=A; x=123; str='Some text!'; y=456; | ||
− | [[File:Printf.svg|right]] | + | [[File:Printf format specifiers.svg|right]] |
− | + | The above is a great example which reflects how the first argument, which is a <code>char</code>, is substituted where the '''%c''' format specifier is used. The second argument, which is an <code>int</code>, is then substituted where the second format specifier, '''%d''', has been used. The third argument, which is of type <code>const char *</code>, is substituted where the third format specifier, '''%s''', has been placed. Likewise, the final argument is an <code>int</code> type; it gets substituted where the '''%d''' format specifier is used. | |
− | The printf() function supports many different types of formats that | + | 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'': | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 100: | Line 104: | ||
</source> | </source> | ||
− | + | '''Executed Output Result''': | |
AA:BB:CC | 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'': | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 114: | Line 119: | ||
</source> | </source> | ||
− | + | '''Executed Output Result''': | |
99% | 99% | ||
=== printf() Safety === | === printf() Safety === | ||
− | Because the printf() function interprets the first argument as the format string, extra precautions must be taken to ensure | + | 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()'''. |
<source lang="C">printf("%s", user_input);</source> | <source lang="C">printf("%s", user_input);</source> | ||
− | == fgets() | + | == fgets() == |
− | 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 | + | 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'': | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 137: | Line 143: | ||
</source> | </source> | ||
− | The example above will prompt the user for a name | + | The example above will prompt the user for a name; it will then store the name in a <code>string</code> type. Finally, the string will be printed to the output stream. Note that we have passed <code>stdin</code> to tell '''fgets()''' that it should be reading from the standard input stream. |
== getchar() - get character == | == getchar() - get character == | ||
− | The '''getchar()''' function performs | + | 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'': | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 152: | Line 159: | ||
</source> | </source> | ||
− | + | Note that the example above ''does not'' take care of '''EOF''' values. | |
− | == scanf() | + | == scanf() == |
− | The '''scanf()''' function performs a task very | + | 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 <code>int</code> values from user input'': | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 169: | Line 177: | ||
</source> | </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 | + | 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 (<code>&a</code> means to take the address of a; this concept is explained more in-depth in the {{C|pointers|pointers guide}}). A sample output of the program above might look like this: |
+ | |||
Please enter two integers separated by a single comma: 1793,430 | Please enter two integers separated by a single comma: 1793,430 | ||
1793 + 430 = 2223 | 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'': | ||
<source lang="C"> | <source lang="C"> | ||
#include <stdio.h> | #include <stdio.h> | ||
Line 187: | Line 197: | ||
</source> | </source> | ||
− | + | 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 | Please enter your name: david | ||
Welcome back david! | Welcome back david! | ||
− | |||
[[Category:C programming language]] | [[Category:C programming language]] | ||
[[Category:File i/o - C]] | [[Category:File i/o - C]] |
Latest revision as of 07:13, 4 January 2015
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.
Contents
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;
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!