เราสามารถเขียนโปรแกรมในภาษา C เพื่อพิมพ์เนื้อหาบางส่วนลงในไฟล์และพิมพ์สิ่งต่อไปนี้ −
- จำนวนอักขระที่ป้อนลงในไฟล์
- ย้อนกลับอักขระที่ป้อนลงในไฟล์
ขั้นแรก ให้ลองเก็บจำนวนอักขระลงในไฟล์โดยเปิดไฟล์ในโหมดเขียน
สำหรับการป้อนข้อมูลลงในไฟล์ เราใช้ตรรกะตามที่ระบุด้านล่าง −
while ((ch = getchar( ))!=EOF) {//after enter data press cntrl+Z to terminate
fputc(ch, fp);
} ด้วยความช่วยเหลือของฟังก์ชัน ftell, กรอกลับ, fseek เราสามารถย้อนกลับเนื้อหาที่เราป้อนลงในไฟล์แล้วได้
ตัวอย่าง
ด้านล่างนี้เป็นโปรแกรม C สำหรับพิมพ์เนื้อหาบางส่วนลงในไฟล์และพิมพ์จำนวนอักขระและย้อนกลับอักขระที่ป้อนลงในไฟล์ -
#include<stdio.h>
int main( ){
FILE *fp;
char ch;
int n,i=0;
fp = fopen ("reverse.txt", "w");
printf ("enter text press ctrl+z of the end");
while ((ch = getchar( ))!=EOF){
fputc(ch, fp);
}
n = ftell(fp);
printf ( "No. of characters entered = %d\n", n);
rewind (fp);
n = ftell (fp);
printf ("fp value after rewind = %d\n",n);
fclose (fp);
fp = fopen ("reverse.txt", "r");
fseek(fp,0,SEEK_END);
n = ftell(fp);
printf ("reversed content is\n");
while(i<n){
i++;
fseek(fp,-i,SEEK_END);
printf("%c",fgetc(fp));
}
fclose (fp);
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter text press ctrl+z of the end TutorialsPoint ^Z No. of characters entered = 18 fp value after rewind = 0 reversed content is tnioPslairotuT