โจทย์
เขียนโปรแกรม C เพื่อ:
- รับข้อมูลจากผู้ใช้และบันทึกลงไฟล์
- นับจำนวนตัวอักษรที่บันทึก
- แสดงข้อมูลย้อนกลับ (Reverse)
หลักการทำงาน
- เปิดไฟล์ในโหมดเขียน (
"w") - ใช้
getchar()รับตัวอักษรทีละตัว จนกว่าจะกด Ctrl+Z (Windows) / Ctrl+D (Linux/Mac) = EOF - ใช้
fputc()เขียนตัวอักษรลงไฟล์ - ใช้
ftell()ดูตำแหน่งปัจจุบัน (= จำนวนไบต์/ตัวอักษร) - ใช้
fseek()และSEEK_ENDย้ายไปปลายไฟล์ แล้วอ่านย้อนหลับด้วยfgetc()
ตัวอย่างโปรแกรมสมบูรณ์
#include <stdio.h>
int main() {
FILE *fp;
char ch;
int n, i = 0;
// 1. เปิดไฟล์เขียน และรับข้อมูลจากผู้ใช้
fp = fopen("reverse.txt", "w");
printf("Enter text (press Ctrl+Z to end):\n");
while ((ch = getchar()) != EOF) {
fputc(ch, fp);
}
// 2. นับจำนวนตัวอักษร
n = ftell(fp);
printf("Number of characters entered = %d\n", n);
// 3. อ่านย้อนกลับ
fclose(fp);
fp = fopen("reverse.txt", "r");
fseek(fp, 0, SEEK_END); // ไปที่ปลายไฟล์
n = ftell(fp); // ขนาดไฟล์
printf("Reversed content:\n");
while (i < n) {
i++;
fseek(fp, -i, SEEK_END); // ย้อนหลังทีละ 1 ไบต์
printf("%c", fgetc(fp));
}
fclose(fp);
return 0;
}
ผลลัพธ์ตัวอย่าง:
Enter text (press Ctrl+Z to end):
TutorialsPoint
^Z
Number of characters entered = 18
Reversed content:
tniuPslairotuT
ฟังก์ชันสำคัญที่ใช้
| ฟังก์ชัน | หน้าที่ |
|---|---|
| fputc(ch, fp) | เขียน 1 ตัวอักษรลงไฟล์ |
| ftell(fp) | คืนตำแหน่งปัจจุบันในไฟล์ (ไบต์) |
| fseek(fp, offset, SEEK_END) | ย้ายตำแหน่งอ่าน/เขียน |
| fgetc(fp) | อ่าน 1 ตัวอักษรจากไฟล์ |
| rewind(fp) | ย้ายกลับไปจุดเริ่มต้นไฟล์ |