Sage-Code Laboratory
index<--

C Input & Output

Most applications receive input, process the data and produce output. Input can be from keyboard, from touch screen or from file. Data processing is internal. Output can be to screen or to file. Input output functions are provided by <stdio.h> library that must be included into your code.

Console functions

For input and output from console we use following functions:

getchar() and putchar()

Read & write one character:

#include <stdio.h>
int main( ) {
    int c;
    printf( "Input one character :");
    c = getchar( );
    printf( "\nOutput one entered: ");
    putchar( c );
    return 0;
}

gets() and puts()

Read and write one string:

#include <stdio.h>
int main( ) {
    char str[10];
    printf( "Input string :");
    gets( str );
    printf( "\nOutput string: ");
    puts( str );
    return 0;
}

scanf() and printf()

Read and write integer and string:

#include <stdio.h>
int main( ) {
    int x;
    printf( "Input integer:\n");
    scanf("%d", &x);
    printf("\nYour integer %d",&x);
    char s[250];
    printf( "Input one string:");
    scanf("%s", &s);
    printf("\nYour string: %s",&s);
    return 0;
}

Note: Observe placeholder symbol % has nothing special about it. It was a random choice to place this symbol along with one other to create a placeholder in string. For this placeholder we can send a value that matches the placeholder position.

Format Specifiers:

String interpolation placeholders are called in C language: format specifiers. These are specific to a data type but also there are several specifiers not data type dependent. Using specifier you control output as well as input using printf() or scanf().

%c character
%d decimal (integer) number (base 10)
%e exponential floating-point number
%f floating-point number
%i integer (base 10)
%o octal number (base 8)
%s a string of characters
%u unsigned decimal (integer) number
%x number in hexadecimal (base 16)
%% print a percent sign
\% print a percent sign

Function signature:

This is the signature of the two functions:

Note: 3 dots "…" is used in a function to denote a variable number of arguments. This must be always the last arguments in a function call. First argument is mandatory while variable arguments are optional.

Controlling alignment

You can control printf() numbers and strings by using a number format between symbol: % and format specifier letter. This is important if you create table like reports where the numbers must fill in a specific number of available spaces.

Examples:

#include <stdio.h>
int main( ) {
 /* right justified with of 10 */
 printf("+----------+\n");
 printf("|%10d|\n", 123);
 printf("|%10d|\n", 12356);
 printf("|%10d|\n", 1234567890);
 printf("+----------+\n");
 /* right justified with of 10 with fill in 0 */
 printf("|%010d|\n", 123);
 printf("|%010d|\n", 12356);
 printf("|%010d|\n", 1234567890);
 printf("+----------+\n");
 /* left justified with of 10 */
 printf("+----------+\n");
 printf("|%-10d|\n", 123);
 printf("|%-10d|\n", 12356);
 printf("|%-10d|\n", 1234567890);
 printf("+----------+\n");
 /* right justified float */
 printf("|%10.2f|\n", 123.123);
 printf("|%10.2f|\n", 12356.123);
 printf("|%10.2f|\n", 1234567890);
 printf("+----------+\n");
 return 0;
}

Working with files

Files are stored on external storage like: disk, usb-stick, dvd-rom, cd-rom, tape drive. The file can be a binary file or a text file. There is a special library in C that provide functions to create and open files, read content of a file and write content into a file.

Writing into a file:

#include <stdio.h>
main() {
    FILE *f; //declare a file f"
    /* open f file */
    f = fopen("test.txt", "w+");
    fprintf(f, "This is test\n");
    fputs("This is test\n", f);
    /* close f file */
    fclose(f);
}

Note: Function fopen() receive two parameters. First is the file name and second is access mode flag. This flag has predefined values. Using sign + will create the file if the file do not exist. Using "w" will open file for writing.

Access modifiers:

First access modifier is used for text files. Second access modifier is used for binary files.

r

rb

Opens an existing text file for reading purpose.

w

wb

Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.

a

ab

Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.

r+

rb+

Opens a text file for both reading and writing.

w+

wb+

Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.

a+

ab+

Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.

Reading from a file:

To read from a file you must open the file using access modifier "r". You can use functions fscanf() or fgets() to read word by word or row by row. Usually you read an entire file using a loop.

#include <stdio.h>
int main() {
    FILE *f; // declare file
    char str[255]; // declare a buffer
    /* open file for read */
    f = fopen("test.txt", "r");
    /* read first word */
    fscanf(f, "%s", str);
    printf("%s\n", str );
    /* read the rest of string */
    fgets(str, 255, (FILE*)f);
    printf("%s\n", str );
    return 0;
}

Reading a bunch of numbers:
Usually you read numbers into array. If the numbers are on multiple columns things are going to be more complex, but in next example we expect numbers to be one/row. 

#include <stdio.h>
int main()
{
    FILE *numbers;
    numbers = fopen("numbers.txt", "r");
    //define a memory model for numbers
    int array[16];
    //read file into array
    int i;
    for (i = 0; i < 16; i++)
    {
        fscanf(numbers, "%d", &array[i]);
        printf("Number is: %d\n\n", array[i]);
    }
    return 0
}

Note: For working with binary files you must check external documentation for functions: fread() and fwrite(). Is not in our scope to teach you these two functions.


Read next: Directives