文件是记录的集合,或者是硬盘上的一个位置,数据永久存储在其中。
文件的必要性
当程序终止时,整个数据将丢失。
存储在文件中会保留数据,即使程序终止也是如此。
如果要输入大量数据,通常需要花费大量时间才能全部输入。
我们可以使用很少的命令轻松访问文件的内容。
您可以轻松地将数据从一台计算机移动到另一台计算机,而无需更改。
通过使用 C 命令,我们可以以不同的方式访问文件。
对文件的操作
C语言编程语言对文件的操作如下−
- 命名文件
- 打开文件
- 从文件中读取
- 写入文件
- 关闭文件
语法
声明文件指针的语法如下
FILE *File pointer;
例如,FILE * fptr;
命名和打开文件指针的语法如下
File pointer = fopen ("File name", "mode");
例如,要附加打开文件的模式,请使用下面给出的语法
FILE *fp;
fp =fopen ("sample.txt", "a");
如果该文件不存在,则将创建一个新文件。
如果文件存在,则当前内容将添加到旧内容中。
程序
以下是用于在追加模式下打开文件并计算文件中存在的行数的 C 程序
#include<stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
//open file in read more
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!
",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='
')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of before adding lines are: %d
",linesCount);
fp=fopen(FILENAME,"a"); //open fine in append mode
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!
",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='
')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of after adding lines are: %d
",linesCount);
return 0;
}
输出
当执行上述程序时,它会产生以下结果
Total number of lines before adding lines are: 3
WELCOME to Tutorials
Its C Programming Language
^Z
Total number of after adding lines are: 8