Text files: write then read
ไฟล์เก็บข้อมูลหลังโปรแกรมจบลง
- file เก็บข้อมูลบน disk, ดังนั้นมันยังคงอยู่หลังจากโปรแกรมของคุณหยุดทำงาน
- คุณทำงานกับ file ผ่าน
FILE *— pointer ที่คุณได้รับจากfopen - ในงานเหล่านี้คุณ เขียน file, แล้ว อ่าน กลับมาในโปรแกรมเดียวกัน, ดังนั้นทุกอย่างจึง self-contained
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("data.txt", "w")เปิด file สำหรับ การเขียน (มันสร้างหรือล้างไฟล์)fopen("data.txt", "r")เปิดมันสำหรับการ อ่าน- เสมอ
fclose(f)เมื่อคุณทำเสร็จ, เพื่อให้ข้อมูลถูกบันทึกและ file ถูกปล่อย
เขียนด้วย fprintf
fprintfทำงานเหมือนprintf, แต่ argแรกคือFILE *fprintf(f, "%d\n", x);เขียนเลขxและ newline เข้า filef- เขียนแต่ละค่าบรรทัดเดียวเพื่อให้อ่านกลับได้ง่าย
อ่านด้วย fscanf และ fgets
fscanf(f, "%d", &x)อ่านหนึ่งตัวเลข; มันคืนค่า1เมื่อสำเร็จfgets(buf, size, f)อ่านหนึ่ง บรรทัด ของข้อความลงในbuf; มันคืนค่าNULLที่ปลาย- Loop จนกว่าการอ่านจะล้มเหลวเพื่อประมวลผลทั้ง file
#include <stdio.h>
int main(void) {
FILE *f = fopen("nums.txt", "w");
fprintf(f, "3\n4\n");
fclose(f);
f = fopen("nums.txt", "r");
if (f == NULL) { // the file could not be opened
printf("cannot open nums.txt\n");
return 1;
}
int x, total = 0;
while (fscanf(f, "%d", &x) == 1) {
total += x;
}
fclose(f);
printf("%d\n", total); // 7
return 0;
}
ข้อผิดพลาดที่พบบ่อย
- ตรวจสอบว่า
fopenไม่ได้คืนค่าNULLก่อนอ่านหรือเขียน - เสมอ
fclosefile เมื่อคุณทำเสร็จ
ลองดูเลย
- งานเหล่านี้เป็น full programs: เขียนภายใน
main, และ Check answer ทดสอบ output - เขียน file ก่อน,
fclose, แล้วเปิดอีกครั้งสำหรับการอ่านและ loop จนกว่าการอ่านจะล้มเหลว
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
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).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
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).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Mode "w" wipes a file; mode "a" appends to the end. The starter writes 10 และ 20. Reopen scores.txt with "a", add the line 30, close it, then read every number back and print the total (60).
คลิก Run เพื่อดูผลลัพธ์ที่นี่