> For the complete documentation index, see [llms.txt](https://skkv-itmo.gitbook.io/c-cpp-cookies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://skkv-itmo.gitbook.io/c-cpp-cookies/best-practices/best-practices/open-files.md).

# 2. Открытие файлов

{% file src="/files/yLy9d7eTReIrmJMqwI8N" %}
Весь приведённый далее код оформлен с использованием clang-format
{% endfile %}

{% code overflow="wrap" lineNumbers="true" %}

```c
int main(int argc, char *argv[])
{
	FILE* inputFile = fopen(argv[1], "r");
	FILE* outputFile = fopen(argv[2], "w");

    // malloc
    // read from input file
    // calculate
    // write to output file
    
    fclose(inputFile);
    fclose(outputFile);
}
```

{% endcode %}

<details>

<summary>Вариант реорганизации и исправления кода</summary>

Освобождайте ресурсы сразу, как они становятся быть ненужными. Более того, если в `calculate` может произойти выходи из программы, то нужно будет освобождать больше ресурсов и не забыть это сделать.

{% code overflow="wrap" lineNumbers="true" %}

```c
int main(int argc, char *argv[])
{
	FILE* inputFile = fopen(argv[1], "r");
    // file is opened?
    // malloc
    // read from input file
    fclose(inputFile);

    // calculate
    
	FILE* outputFile = fopen(argv[2], "w");
    // file is opened?    
    // write to output file
    fclose(outputFile);
}
```

{% endcode %}

</details>
