为什么 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