# File I/O (Input/Output)

## **File I/O in C**

**Opening and Closing Files**

To work with files, you first need to open them using the `fopen` function and close them with `fclose`.

**Syntax for `fopen`:**

```c
FILE *fopen(const char *filename, const char *mode);
```

* **`filename`**: Name of the file.
* **`mode`**: File access mode (e.g., `"r"` for reading, `"w"` for writing).

**Syntax for `fclose`:**

```c
int fclose(FILE *stream);
```

* **`stream`**: Pointer to the `FILE` object.

**Example: Opening and Closing Files**

```c
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");  // Open file for writing
    
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    
    // Write to the file
    fprintf(file, "Hello, World!\n");
    
    // Close the file
    fclose(file);
    
    return 0;
}
```

***

#### **Reading from Files**

To read data from a file, use functions like `fscanf`, `fgets`, and `fread`.

**Syntax for `fscanf`:**

```c
int fscanf(FILE *stream, const char *format, ...);
```

* **`stream`**: Pointer to the `FILE` object.
* **`format`**: Format string similar to `printf`.

**Syntax for `fgets`:**

```c
char *fgets(char *str, int n, FILE *stream);
```

* **`str`**: Buffer to store the string.
* **`n`**: Maximum number of characters to read.
* **`stream`**: Pointer to the `FILE` object.

**Syntax for `fread`:**

```c
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
```

* **`ptr`**: Pointer to the memory where data will be read.
* **`size`**: Size of each item to read.
* **`count`**: Number of items to read.
* **`stream`**: Pointer to the `FILE` object.

**Example: Reading from a File**

```c
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");  // Open file for reading
    
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    
    char buffer[100];
    
    // Read the file line by line
    while (fgets(buffer, sizeof(buffer), file)) {
        printf("%s", buffer);
    }
    
    // Close the file
    fclose(file);
    
    return 0;
}
```

***

#### **Writing to Files**

To write data to a file, use functions like `fprintf`, `fputs`, and `fwrite`.

**Syntax for `fprintf`:**

```c
int fprintf(FILE *stream, const char *format, ...);
```

* **`stream`**: Pointer to the `FILE` object.
* **`format`**: Format string similar to `printf`.

**Syntax for `fputs`:**

```c
int fputs(const char *str, FILE *stream);
```

* **`str`**: String to write.
* **`stream`**: Pointer to the `FILE` object.

**Syntax for `fwrite`:**

```c
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
```

* **`ptr`**: Pointer to the data to write.
* **`size`**: Size of each item to write.
* **`count`**: Number of items to write.
* **`stream`**: Pointer to the `FILE` object.

**Example: Writing to a File**

```c
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");  // Open file for writing
    
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    
    // Write to the file
    fprintf(file, "Hello, File I/O!\n");
    fputs("Writing using fputs.\n", file);
    
    // Close the file
    fclose(file);
    
    return 0;
}
```

***

#### **Error Handling**

Error handling is crucial for robust file operations. Use `ferror` and `clearerr` to check and clear errors.

**Syntax for `ferror`:**

```c
int ferror(FILE *stream);
```

* **`stream`**: Pointer to the `FILE` object.

**Syntax for `clearerr`:**

```c
void clearerr(FILE *stream);
```

* **`stream`**: Pointer to the `FILE` object.

**Example: Error Handling**

```c
#include <stdio.h>

int main() {
    FILE *file = fopen("nonexistent.txt", "r");  // Try to open a non-existent file
    
    if (file == NULL) {
        perror("Error opening file");  // Print error message
        return 1;
    }
    
    // Perform file operations...
    
    if (ferror(file)) {
        printf("Error reading file\n");
    }
    
    clearerr(file);  // Clear error indicators
    
    fclose(file);
    
    return 0;
}
```

**Explanation:**

* **`perror`**: Prints a descriptive error message based on the current value of `errno`.
* **`ferror`**: Checks if an error occurred on the file stream.
* **`clearerr`**: Clears the error indicators for the file stream.

***

#### **Summary**

* **Opening and Closing Files**: Use `fopen` and `fclose`.
* **Reading Files**: Use `fscanf`, `fgets`, and `fread`.
* **Writing Files**: Use `fprintf`, `fputs`, and `fwrite`.
* **Error Handling**: Use `ferror`, `clearerr`, and `perror` to handle and report errors.


---

# 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/file-i-o-input-output.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.
