# I/O in C

## Chapter: Input and Output in C

***

Input and output (I/O) operations are essential in any program, as they allow interaction with the user or external devices. In C, I/O operations are handled using functions from the **standard input/output library (`<stdio.h>`)**. This chapter covers various methods for reading inputs and displaying outputs, ranging from simple console I/O to working with files.

***

### 1. Introduction to I/O in C

C provides three standard streams for input and output:

* **Standard Input (`stdin`)**: Used for reading input, typically from the keyboard.
* **Standard Output (`stdout`)**: Used for displaying output, typically to the screen.
* **Standard Error (`stderr`)**: Used for error messages or diagnostics.

The most commonly used I/O functions in C are:

* `printf` and `scanf` for formatted I/O.
* `putchar` and `getchar` for character-based I/O.
* `puts` and `gets` for string-based I/O.

***

### 2. Console Input and Output

#### 2.1 Printing Output with `printf`

The `printf` function is used for formatted output.

**Syntax**:

```c
printf("format string", arguments);
```

* The **format string** contains text and format specifiers (e.g., `%d`, `%s`) to display variables.
* The **arguments** correspond to the format specifiers.

**Example**:

```c
#include <stdio.h>

int main() {
    int age = 25;
    float height = 5.9;

    printf("Age: %d\n", age);
    printf("Height: %.1f\n", height);

    return 0;
}
```

**Output**:

```
Age: 25
Height: 5.9
```

**Common Format Specifiers:**

| Specifier | Description           | Example           |
| --------- | --------------------- | ----------------- |
| `%d`      | Integer               | `123`             |
| `%f`      | Floating-point number | `123.45`          |
| `%c`      | Character             | `'A'`             |
| `%s`      | String                | `"Hello"`         |
| `%x`      | Hexadecimal           | `7b` (for `123`)  |
| `%o`      | Octal                 | `173` (for `123`) |
| `%%`      | Prints `%` character  | `%`               |

***

#### 2.2 Reading Input with `scanf`

The `scanf` function is used to read formatted input.

**Syntax**:

```c
scanf("format string", &variable);
```

* The **format string** specifies the data type of the input.
* The **`&`** (address-of operator) is used to pass the memory address of the variable where the input will be stored.

**Example**:

```c
#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);

    return 0;
}
```

**Output**:

```
Enter a number: 42
You entered: 42
```

**Notes on `scanf`:**

1. Multiple inputs can be read at once:

   ```c
   scanf("%d %f", &int_var, &float_var);
   ```
2. `scanf` stops reading strings at spaces. Use `fgets` for multi-word input.

***

#### 2.3 Character Input and Output

For single-character I/O, use `getchar` and `putchar`.

1. **`getchar`**: Reads a single character from the input.

   **Example**:

   ```c
   char ch = getchar();
   ```
2. **`putchar`**: Prints a single character to the output.

   **Example**:

   ```c
   putchar('A');
   ```

**Example Program**:

```c
#include <stdio.h>

int main() {
    char ch;

    printf("Enter a character: ");
    ch = getchar();

    printf("You entered: ");
    putchar(ch);
    printf("\n");

    return 0;
}
```

**Output**:

```
Enter a character: G
You entered: G
```

***

#### 2.4 String Input and Output

1. **`gets`**: Reads an entire line, including spaces. **Avoid `gets`**, as it can cause buffer overflows.
2. **`fgets`** (Preferred): Reads a line of text safely, including spaces.

   **Example**:

   ```c
   char str[50];
   fgets(str, sizeof(str), stdin);
   ```
3. **`puts`**: Prints a string followed by a newline.

   **Example**:

   ```c
   puts("Hello, World!");
   ```

**Example Program**:

```c
#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);

    printf("Hello, ");
    puts(name);

    return 0;
}
```

***

### 3. File Input and Output

File I/O allows reading from and writing to files. The `<stdio.h>` library provides functions like `fopen`, `fprintf`, `fscanf`, `fclose`, etc.

#### 3.1 Opening and Closing Files

Use `fopen` to open a file:

```c
FILE *file_pointer = fopen("filename", "mode");
```

Modes include:

* `"r"`: Read mode.
* `"w"`: Write mode (overwrites the file).
* `"a"`: Append mode.
* `"r+"`: Read and write.

Use `fclose` to close the file:

```c
fclose(file_pointer);
```

***

#### 3.2 Writing to a File

Use `fprintf` or `fputs` for writing data to a file.

**Example**:

```c
#include <stdio.h>

int main() {
    FILE *fp = fopen("output.txt", "w");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    fprintf(fp, "Hello, File!\n");
    fclose(fp);

    return 0;
}
```

***

#### 3.3 Reading from a File

Use `fscanf` or `fgets` to read data from a file.

**Example**:

```c
#include <stdio.h>

int main() {
    FILE *fp = fopen("output.txt", "r");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    char buffer[100];
    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("%s", buffer);
    }

    fclose(fp);
    return 0;
}
```

***

### 4. Formatted and Unformatted I/O

#### 4.1 Formatted I/O

Formatted I/O functions, like `printf` and `scanf`, allow the use of format specifiers for structured data input and output.

#### 4.2 Unformatted I/O

Unformatted I/O functions, like `getchar`, `putchar`, `gets`, and `puts`, deal directly with raw data.

***

### 5. Best Practices for I/O in C

1. **Validate Inputs**: Always check for valid inputs to prevent errors or undefined behavior.
2. **Handle File Errors**: Check file pointers for `NULL` after `fopen`.
3. **Use Safe Functions**: Prefer `fgets` over `gets`, as it avoids buffer overflows.
4. **Close Files**: Always close files after reading or writing.

***

### 6. Sample Questions and Solutions

#### Question 1: Write a program to read and print a sentence using `fgets` and `puts`.

**Solution**:

```c
#include <stdio.h>

int main() {
    char sentence[100];

    printf("Enter a sentence: ");
    fgets(sentence, sizeof(sentence), stdin);

    printf("You entered: ");
    puts(sentence);

    return 0;
}
```

***

#### Question 2: Write a program to copy content from one file to another.

**Solution**:

```c
#include <stdio.h>

int main() {
    FILE *source, *destination;
    char ch;

    source = fopen("source.txt", "r");
    if (source == NULL) {
        printf("Error opening source file.\n");
        return 1;
    }

    destination = fopen("destination.txt", "w");
    if (destination == NULL) {
        printf("Error opening destination file.\n");
        fclose(source);
        return 1;
    }

    while ((ch = fgetc(source)) != EOF) {
        fputc(ch, destination);
    }

    fclose(source);
    fclose(destination);

    printf("File copied successfully.\n");
    return 0;
}
```

***

### Summary

Input and output operations are fundamental for creating interactive and file-based C programs. In this chapter, we covered console I/O using `printf`, `scanf`, `getchar`, and `putchar`, as well as file I/O with `fopen`, `fscanf`, and `fprintf`. By understanding these concepts, you can create robust programs that interact with users and external files. Practice the sample questions to solidify your skills.

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.d19.in/c-programming/basics/i-o-in-c.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
