ไฟล์ (File) คือที่เก็บข้อมูลถาวร การใช้ไฟล์ช่วย: รักษาข้อมูล, เข้าถึงข้อมูลจำนวนมาก, ย้ายข้อมูลระหว่างเครื่อง
โหมด Write ("w")
FILE *fp;
fp = fopen("sample.txt", "w");
- ถ้าไฟล์ไม่มี -> สร้างไฟล์ใหม่
- ถ้าไฟล์มี -> ลบข้อมูลเก่าทิ้ง และเริ่มเขียนใหม่ (Truncate)
โปรแกรม 1: บันทึกชื่อและคะแนนนักเรียนลงไฟล์
#include <stdio.h>
int main() {
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr = fopen("std.txt", "w");
if (fptr == NULL) {
printf("Error!");
return 1;
}
for (i = 0; i < num; i++) {
printf("For student %d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr, "\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}
โปรแกรม 2: บันทึกรายละเอียดพนักงานและอ่านกลับมาแสดง
#include <stdio.h>
int main() {
FILE *fp;
int eno;
char ename[30];
float sal;
fp = fopen("emp.txt", "w");
printf("Enter eno, ename, sal: ");
scanf("%d %s %f", &eno, ename, &sal);
fprintf(fp, "%d %s %f", eno, ename, sal);
fclose(fp);
fp = fopen("emp.txt", "r");
fscanf(fp, "%d %s %f", &eno, ename, &sal);
printf("Employee no: %d\n", eno);
printf("Employee name: %s\n", ename);
printf("Salary: %f\n", sal);
fclose(fp);
return 0;
}
ผลลัพธ์
Run 1: Enter number of students: 3 For student1 Enter name: lucky Enter marks: 59 For student2 Enter name: pinky Enter marks: 89 For student3 Enter name: bob Enter marks: 45 Run 2: enter the details of eno, ename, sal: 1 Pinky 34000 employee no: = 1 employee name = Pinky salary = 34000.000000