Text files: write then read · Текстовые файлы: запись, затем чтение
Files keep data after the program ends
- A file stores data on disk, so it is still there after your program stops.
- You work with a file through a
FILE *— a pointer you get fromfopen. - In these tasks you write a file, then read it back in the same program, so everything is self-contained.
Файлы сохраняют данные после завершения программы
- Файл хранит данные на диске, поэтому они остаются там после остановки вашей программы.
- Вы работаете с файлом через
FILE *— указатель, который вы получаете отfopen. - В этих задачах вы записываете файл, затем читаете его обратно в той же программе, так что всё самодостаточно.
Writing then reading a file · Запись, затем чтение файла
A file is used in three steps: open it with fopen, read or write, then close it with fclose. · Файл используется в три этапа: открыть его с помощью fopen, читать или записывать, затем закрыть с помощью fclose.
Opening and closing
fopen("data.txt", "w")opens a file for writing (it creates or empties the file).fopen("data.txt", "r")opens it for reading.- Always
fclose(f)when you are done, so the data is saved and the file is released.
Открытие и закрытие
fopen("data.txt", "w")открывает файл для записи (он создает или очищает файл).fopen("data.txt", "r")открывает его для чтения.- Всегда
fclose(f), когда закончите, чтобы данные были сохранены, а файл освобожден.
Writing with fprintf
fprintfworks likeprintf, but its first argument is theFILE *.fprintf(f, "%d\n", x);writes the numberxand a newline into the filef.- Write each value on its own line so it is easy to read back.
Запись с помощью fprintf
fprintfработает какprintf, но его первый аргумент — этоFILE *.fprintf(f, "%d\n", x);записывает числоxи символ новой строки в файлf.- Записывайте каждое значение на отдельной строке, чтобы было легко читать обратно.
Reading with fscanf and fgets
fscanf(f, "%d", &x)reads one number; it returns1when it succeeds.fgets(buf, size, f)reads one line of text intobuf; it returnsNULLat the end.- Loop until the read fails to process the whole file.
Чтение с помощью fscanf и fgets
fscanf(f, "%d", &x)читает одно число; он возвращает1при успехе.fgets(buf, size, f)читает одну строку текста вbuf; он возвращаетNULLв конце.- Цикл продолжается, пока чтение не завершится, чтобы обработать весь файл.
#include <stdio.h>
int main(void) {
FILE *f = fopen("nums.txt", "w");
fprintf(f, "3\n4\n");
fclose(f);
f = fopen("nums.txt", "r");
int x, total = 0;
while (fscanf(f, "%d", &x) == 1) {
total += x;
}
fclose(f);
printf("%d\n", total); // 7
return 0;
}
Common mistakes
- Check that
fopendid not returnNULLbefore reading or writing. - Always
fclosethe file when you are done.
Распространенные ошибки
- Проверяйте, что
fopenне вернулNULL, перед чтением или записью. - Всегда
fcloseфайл, когда закончите работу.
Now you try
- These tasks are full programs: write inside
main, and Check answer tests the output. - Write the file first,
fcloseit, then open it again for reading and loop until the read fails.
Теперь попробуйте сами
- Эти задачи представляют собой полные программы: пишите внутри
main, а кнопка Check answer проверяет вывод. - Сначала запишите файл,
fcloseего, затем откройте снова для чтения и запускайте цикл, пока чтение не завершится.
In main: write the numbers 10, 20, 5, 7 (one per line) to a file, close it, then open it again and add them up with fscanf. Print the total (42). · В блоке main: запишите числа 10, 20, 5, 7 (каждое с новой строки) в файл, закройте его, затем снова откройте и сложите их с помощью fscanf. Выведите сумму (42).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
In main: write three lines of text to a file, close it, then open it again and count the lines with fgets. Print the count (3). · В блоке main: запишите три строки текста в файл, закройте его, затем снова откройте и подсчитайте количество строк с помощью fgets. Выведите счетчик (3).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.