เปิดไฟล์ในโหมดการอ่าน หากมีไฟล์อยู่ ให้เขียนโค้ดเพื่อนับจำนวนบรรทัดในไฟล์ หากไม่มีไฟล์ แสดงว่าไฟล์นั้นไม่มีข้อผิดพลาด
ไฟล์นี้เป็นชุดของบันทึก (หรือ) เป็นที่บนฮาร์ดดิสก์ที่จัดเก็บข้อมูลอย่างถาวร
ต่อไปนี้เป็นการดำเนินการกับไฟล์ -
-
การตั้งชื่อไฟล์
-
กำลังเปิดไฟล์
-
อ่านจากไฟล์
-
เขียนลงในไฟล์
-
การปิดไฟล์
ไวยากรณ์
ต่อไปนี้เป็นรูปแบบการเปิดและตั้งชื่อไฟล์ -
1) FILE *File pointer;
Eg : FILE * fptr;
2) File pointer = fopen ("File name", "mode");
Eg : fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w"); โปรแกรมที่ 1
#include <stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
//open file in read more
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
} ผลลัพธ์
Total number of lines are: 3 Note: employee details.txt file consist of Pinky 20 5000.000000 Here total number of line are 3
โปรแกรม 2
ในโปรแกรมนี้ เราจะมาดูวิธีค้นหาจำนวนบรรทัดทั้งหมดในไฟล์ที่ไม่มีอยู่ในโฟลเดอร์
#include <stdio.h>
#define FILENAME "sample.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
//open file in write mode
fp=fopen(FILENAME,"w");
printf ("enter text press ctrl+z of the end");
while ((ch = getchar( ))!=EOF){
fputc(ch, fp);
}
fclose(fp);
//open file in read more
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
} ผลลัพธ์
enter text press ctrl+z of the end Hi welcome to Tutorials Point C Pogramming Question & answers ^Z Total number of lines are: 2