文件是记录的集合,或者是硬盘上的一个位置,数据永久存储在其中。
文件的必要性
当程序终止时,整个数据将丢失。
存储在文件中会保留数据,即使程序终止也是如此。
如果要输入大量数据,通常需要花费大量时间才能全部输入。
我们可以使用很少的命令轻松访问文件的内容。
您可以轻松地将数据从一台计算机移动到另一台计算机,而无需更改。
通过使用 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