Должно быть, вы думаете: "Это всего лишь выводит текст на экран. С какой стати это файловый ввод/вывод"? Ответ кажется поначалу неочевидным и требует некоторых знаний о системе UNIX. С точки зрения UNIX все является файлом, в том смысле, что вы можете читать из него и записывать в него. Это значит, что принтер может быть отождествлен с файлом, так как все, что вы делаете с принтером - пишете в него. Также полезно думать об этих файлах как о потоках, поскольку, как будет показано позже, их можно перенаправлять с помощью оболочки.
Когда вы вызываете `printf`, на самом деле происходит запись в специальный файл `stdout`, сокращение от __standard output (стандартный вывод)__.
`stdout` представляет собой, что неудивительно, средство стандартного вывода по выбору вашей оболочки, роль которой чаще всего играет терминал. Это объясняет почему он выводит символы на экран.
### Rudimentary File IO, or How I Learnt to Lay Pipes
Enough theory, let's get down to business by writing some code!
The easist way to write to a file is to redirect the output stream using the output redirect tool, `>`.
If you want to append, you can use `>>`. _N.b. these redirection operators are in_`bash`_and similar shells._
```
удар
# Это будет выводиться на экран ...
./Привет, мир
# ... но это будет записываться в файл!
./helloworld> hello.txt
```
The contents of `hello.txt` will, not surprisingly, be
```
Привет, мир!
```
Say we have another program called `greet`, similar to `helloworld`, that greets you given your name.
```
с
# включают
# включают
int main () { // Инициализировать массив для хранения имени. char name \[20\]; // Прочитайте строку и сохраните ее для ее имени. scanf ("% s", имя); // Печать приветствия. printf («Привет,% s!», имя); return EXIT\_SUCCESS; }
```
Instead of reading from the keyboard, we can redirect `stdin` to read from a file using the `<` tool.
```
удар
# Напишите файл с именем.
echo Kamala> name.txt
# Это будет читать имя из файла и распечатывать приветствие на экране.
./greet <имя.txt
# \==> Привет, Камала!
# Если вы хотите также записать приветствие в файл, вы можете сделать это, используя «>».
```
### The Real Deal
The above methods only worked for the most basic of cases. If you wanted to do bigger and better things, you will probably want to work with files from within C instead of through the shell.
To accomplish this, you will use a function called `fopen`. This function takes two string parameters, the first being the file name and the second being the mode.
Mode is basically permissions, so `r` for read, `w` for write, `a` for append. You can also combine them, so `rw` would mean you could read and write to the file. There are more modes, but these are the most used.
After you have a `FILE` pointer, you can use basically the same IO commands you would've used, except that you have to prefix them with `f` and the first argument will be the file pointer.
For example, `printf`'s file version is `fprintf`.
Here's a program called `greetings` that reads a from a file containing a list of names and writes to another file the greetings.