解釋C語言中檔案的寫入模式操作
檔案是記錄的集合,或者說是硬碟上永久儲存資料的地方。
檔案的必要性
程式終止時,所有資料都會丟失。
將資料儲存在檔案中,即使程式終止,資料也能保留。
如果您想輸入大量資料,通常需要花費大量時間來輸入所有資料。
我們可以很容易地使用一些命令來訪問檔案的內容。
您可以輕鬆地將資料從一臺計算機移動到另一臺計算機,而無需更改。
使用C語言命令,我們可以透過不同的方式訪問檔案。
檔案操作
C語言中的檔案操作如下:
- 命名檔案
- 開啟檔案
- 從檔案讀取
- 寫入檔案
- 關閉檔案
語法
宣告檔案指標的語法如下:
FILE *File pointer;
例如,FILE * fptr;
命名和開啟檔案指標的語法如下:
File pointer = fopen ("File name", "mode");例如:
FILE *fp;
fp = fopen ("sample.txt", "w");程式1
下面是一個C程式,用於讀取n個學生的姓名和分數,並將它們儲存在一個檔案中:
#include <stdio.h>
int main(){
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("std.txt", "w")); // opening file in write mode
if(fptr == NULL){
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i){
printf("For student%d
Enter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"
Name: %s
Marks=%d
", name, marks);
}
fclose(fptr);
return 0;
}輸出
執行上述程式後,會產生以下結果:
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
程式2
下面是一個C程式,用於將員工資訊儲存在一個檔案中,並列印相同的資訊:
#include<stdio.h>
int main ( ){
FILE *fp;
int eno;
char ename[30];
float sal;
fp =fopen ("emp.txt", "w"); // opening file in write mode
printf ("enter the details of 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
", eno);
printf ("employee name = %s
", ename);
printf ("salary = %f
", sal);
fclose (fp);
return 0;
}輸出
執行上述程式後,會產生以下結果:
enter the details of eno, ename, sal:1 Pinky 34000 employee no: = 1 employee name = Pinky salary = 34000.000000
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP