ไฟล์คือตำแหน่งหน่วยเก็บข้อมูลจริงบนดิสก์ และไดเร็กทอรีเป็นพาธแบบลอจิคัลที่ใช้ในการจัดระเบียบไฟล์ มีไฟล์อยู่ภายในไดเร็กทอรี
การดำเนินการสามอย่างที่เราสามารถทำได้ในไฟล์มีดังนี้ -
- เปิดไฟล์
- ไฟล์ประมวลผล (อ่าน เขียน แก้ไข)
- บันทึกและปิดไฟล์
ตัวอย่าง
ลองพิจารณาตัวอย่างด้านล่าง −
- เปิดไฟล์ในโหมดเขียน
- ป้อนคำสั่งในไฟล์
อินพุต ไฟล์มีดังนี้ −
Hi welcome to my world This is C programming tutorial From tutorials Point
ผลลัพธ์ เป็นดังนี้ −
Number of characters = 72
Total words = 13
Total lines = 3
โปรแกรม
ต่อไปนี้เป็นโปรแกรม C เพื่อ นับอักขระ บรรทัด และจำนวนคำในไฟล์ −
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * file;
char path[100];
char ch;
int characters, words, lines;
file=fopen("counting.txt","w");
printf("enter the text.press cntrl Z:\n");
while((ch = getchar())!=EOF){
putc(ch,file);
}
fclose(file);
printf("Enter source file path: ");
scanf("%s", path);
file = fopen(path, "r");
if (file == NULL){
printf("\nUnable to open file.\n");
exit(EXIT_FAILURE);
}
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF){
characters++;
if (ch == '\n' || ch == '\0')
lines++;
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
if (characters > 0){
words++;
lines++;
}
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
fclose(file);
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter the text.press cntrl Z: Hi welcome to Tutorials Point C programming Articles Best tutorial In the world Try to have look on it All The Best ^Z Enter source file path: counting.txt Total characters = 116 Total words = 23 Total lines = 6