ไฟล์คือชุดของบันทึก (หรือ) เป็นที่บนฮาร์ดดิสก์ซึ่งข้อมูลจะถูกเก็บไว้อย่างถาวร ด้วยการใช้คำสั่ง C เราเข้าถึงไฟล์ได้หลายวิธี
ความต้องการของไฟล์ในภาษา C
-
ข้อมูลทั้งหมดจะหายไปเมื่อโปรแกรมหยุดทำงาน และการจัดเก็บในไฟล์จะรักษาข้อมูลของคุณแม้ว่าโปรแกรมจะยุติลง
-
หากคุณต้องการใส่ข้อมูลจำนวนมาก ปกติจะใช้เวลามากในการป้อนข้อมูลทั้งหมด
-
หากคุณมีไฟล์ที่มีข้อมูลทั้งหมด คุณสามารถเข้าถึงเนื้อหาของไฟล์ได้อย่างง่ายดายโดยใช้คำสั่งไม่กี่คำสั่งใน C.
-
คุณสามารถย้ายข้อมูลจากคอมพิวเตอร์เครื่องหนึ่งไปยังอีกเครื่องหนึ่งได้อย่างง่ายดายโดยไม่มีการเปลี่ยนแปลง
การทำงานของไฟล์
การดำเนินการที่สามารถดำเนินการกับไฟล์ในภาษา C ได้มีดังนี้ −
- การตั้งชื่อไฟล์
- กำลังเปิดไฟล์
- การอ่านจากไฟล์
- กำลังเขียนลงในไฟล์
- กำลังปิดไฟล์
ไวยากรณ์
ไวยากรณ์สำหรับการเปิดและตั้งชื่อไฟล์ เป็นดังนี้ −
FILE *File pointer;
ตัวอย่างเช่น FILE * fptr;
File pointer = fopen ("File name”, "mode”); ตัวอย่างเช่น fptr =fopen ("sample.txt", "r")
FILE *fp;
fp = fopen ("sample.txt”, "w”); ไวยากรณ์สำหรับ การอ่านจากไฟล์ เป็นดังนี้ −
int fgetc( FILE * fp );// read a single character from a file
ไวยากรณ์สำหรับ การเขียนลงในไฟล์ เป็นดังนี้ −
int fputc( int c, FILE *fp ); // write individual characters to a stream
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C เพื่อแสดงไฟล์ -
#include<stdio.h>
void main(){
//Declaring File//
FILE *femp;
char empname[50];
int empnum;
float empsal;
char temp;
//Opening File and writing into it//
femp=fopen("Employee Details.txt","w");
//Writing User I/p into the file//
printf("Enter the name of employee : ");
gets(empname);
//scanf("%c",&temp);
printf("Enter the number of employee : ");
scanf("%d",&empnum);
printf("Enter the salary of employee : ");
scanf("%f",&empsal);
//Writing User I/p into the file//
fprintf(femp,"%s\n",empname);
fprintf(femp,"%d\n",empnum);
fprintf(femp,"%f\n",empsal);
//Closing the file//
fclose(femp);
//Opening File and reading from it//
femp=fopen("Employee Details.txt","r");
//Reading O/p from the file//
fscanf(femp,"%s",empname);
//fscanf(femp,"%d",&empnum);
//fscanf(femp,"%f",&empsal);
//Printing O/p//
printf("employee name is : %s\n",empname);
printf("employee number is : %d\n",empnum);
printf("employee salary is : %f\n",empsal);
//Closing File//
fclose(femp);
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter the name of employee : Pinky Enter the number of employee : 20 Enter the salary of employee : 5000 employee name is : Pinky employee number is : 20 employee salary is : 5000.000000