ขั้นแรก เปิดไฟล์ในโหมดเขียน หลังจากนั้น ให้ป้อนข้อความจนกว่าจะถึงจุดสิ้นสุดไฟล์ (EOF) เช่น กด ctrlZ เพื่อปิดไฟล์
เปิดอีกครั้งในโหมดการอ่าน จากนั้น อ่านคำจากไฟล์และพิมพ์แต่ละคำในบรรทัดแยกกัน แล้วปิดไฟล์
ตรรกะที่เราใช้พิมพ์หนึ่งคำต่อบรรทัดมีดังนี้ -
while ((ch=getc(fp))!=EOF){
if(fp){
char word[100];
while(fscanf(fp,"%s",word)!=EOF) // read words from file{
printf("%s\n", word); // print each word on separate lines.
}
fclose(fp); // close file.
}
} ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C เพื่อแสดงข้อความทั้งหมดหนึ่งคำต่อบรรทัด -
#include<stdio.h>
int main(){
char ch;
FILE *fp;
fp=fopen("file.txt","w"); //open the file in write mode
printf("enter the text then press cntrl Z:\n");
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen("file.txt","r");
printf("text on the file:\n");
while ((ch=getc(fp))!=EOF){
if(fp){
char word[100];
while(fscanf(fp,"%s",word)!=EOF) // read words from file{
printf("%s\n", word); // print each word on separate lines.
}
fclose(fp); // close file.
}
Else{
printf("file doesnot exist");
// then tells the user that the file does not exist.
}
}
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter the text then press ctrl Z: Hi Hello Welcome To My World ^Z text on the file: Hi Hello Welcome To My World