為什麼 C 程式語言需要檔案?
檔案是記錄的集合(或)硬碟上的一個位置,資料永久儲存在那裡。透過使用 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
",empname);
fprintf(femp,"%d
",empnum);
fprintf(femp,"%f
",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
",empname);
printf("employee number is : %d
",empnum);
printf("employee salary is : %f
",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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP