ไฟล์คือชุดของบันทึก (หรือ) เป็นที่บนฮาร์ดดิสก์ซึ่งข้อมูลจะถูกเก็บไว้อย่างถาวร ด้วยการใช้คำสั่ง 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>
#include <stdlib.h> // For exit()
int main(){
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s",filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL){
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL){
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF){
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter the filename to open for reading file3.txt Enter the filename to open for writing file1.txt Contents copied to file1.txt