Standard I/O functions (printf, scanf, fprintf, fscanf, etc.)

Lesson 7.3: Standard I/O Functions (printf, scanf, fprintf, fscanf, etc.)


C provides a set of standard input/output (I/O) functions in the <stdio.h> library to help you interact with the console (standard input and output streams) and files. These functions make it easy to read and write data in various formats.


1. Standard Output Functions


printf():


Purpose: Prints formatted output to the standard output stream (usually the console).

Syntax:

C

printf("format string", variable1, variable2, ...);

Example:

C

int age = 30;

double salary = 55000.50;

printf("Age: %d, Salary: $%.2f\n", age, salary); 


fprintf():


Purpose: Prints formatted output to a specified file stream.

Syntax:

C

fprintf(filePointer, "format string", variable1, variable2, ...);

Example:

C

FILE *fptr = fopen("output.txt", "w");

fprintf(fptr, "Writing to file: %d\n", 123);

fclose(fptr); 

Use code with caution.

content_copy

2. Standard Input Functions


scanf():


Purpose: Reads formatted input from the standard input stream (usually the keyboard).

Syntax:

C

scanf("format string", &variable1, &variable2, ...);


Example:

C

int num;

printf("Enter a number: ");

scanf("%d", &num);  

Use code with caution.

content_copy

fscanf():


Purpose: Reads formatted input from a specified file stream.

Syntax:

C

fscanf(filePointer, "format string", &variable1, &variable2, ...);

Example:

C

FILE *fptr = fopen("input.txt", "r");

int num;

fscanf(fptr, "%d", &num); 

fclose(fptr);

Common Format Specifiers


Specifier Description

%d Integer

%f Floating-point number (decimal)

%c Single character

%s String (character array)

%u Unsigned integer

%x or %X Hexadecimal number (lowercase or uppercase)

%o Octal number

%% Prints a literal '%' sign


Error Handling and Return Values


printf() and fprintf(): Return the number of characters printed or a negative value if an error occurs.

scanf() and fscanf(): Return the number of input items successfully matched and assigned, or EOF if an error or end-of-file is encountered.


Important Notes:


Ampersand (&): Use the address-of operator (&) before variable names in scanf() and fscanf() to allow the functions to modify the original values.

Buffer Overflows: Be cautious about buffer overflows when reading strings with scanf() and fscanf(). Use width specifiers (e.g., %19s) to limit input to the size of your character array.

Let me know if you'd like any clarification or more examples on this topic!

Course Syllabus