Text files: write then read · Tệp văn bản: ghi rồi đọc
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.
Tập tin giữ dữ liệu sau khi chương trình kết thúc
- Một tập tin lưu trữ dữ liệu trên ổ đĩa, nên nó vẫn còn đó sau khi chương trình của bạn dừng lại.
- Bạn thao tác với tập tin thông qua một
FILE *— một con trỏ bạn nhận được từfopen. - Trong các bài tập này, bạn ghi một tập tin, sau đó đọc lại nó trong cùng chương trình, nên mọi thứ đều tự chứa.
Writing then reading a file · Ghi rồi đọc một tệp
A file is used in three steps: open it with fopen, read or write, then close it with fclose. · Một tệp được sử dụng qua ba bước: mở nó bằng fopen, đọc hoặc ghi, sau đó đóng nó bằng 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.
Mở và đóng
fopen("data.txt", "w")mở một tập tin để ghi (nó tạo mới hoặc xóa trắng tập tin).fopen("data.txt", "r")mở nó để đọc.- Luôn
fclose(f)khi bạn hoàn thành, để dữ liệu được lưu và tệp được giải phóng.
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.
Ghi bằng fprintf
fprintfhoạt động giống nhưprintf, nhưng đối số đầu tiên làFILE *.fprintf(f, "%d\n", x);ghi sốxvà ký tự xuống dòng vào tập tinf.- Ghi mỗi giá trị trên một dòng riêng biệt để dễ dàng đọc lại.
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.
Đọc bằng fscanf và fgets
fscanf(f, "%d", &x)đọc một số; nó trả về1khi thành công.fgets(buf, size, f)đọc một dòng văn bản vàobuf; nó trả vềNULLở cuối.- Lặp lại cho đến khi việc đọc thất bại để xử lý hết toàn bộ tập tin.
#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.
Lỗi thường gặp
- Kiểm tra xem
fopencó trả vềNULLhay không trước khi đọc hoặc ghi. - Luôn đóng
fclosetập tin khi bạn hoàn tất.
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.
Bây giờ bạn thử
- Các bài tập này là đầy đủ chương trình: hãy viết bên trong
main, và Check answer (Kiểm tra đáp án) sẽ thử nghiệm đầu ra. - Viết tệp trước,
fclosenó, sau đó mở lại để đọc và lặp cho đến khi việc đọc thất bại.
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). · Trong main: ghi các số 10, 20, 5, 7 (mỗi số một dòng) vào một tệp, đóng nó, sau đó mở lại và cộng chúng với fscanf. In tổng (42).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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). · Trong main: ghi ba dòng văn bản vào một tệp, đóng nó, sau đó mở lại và đếm số dòng với fgets. In số đếm (3).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.