C语言中文件的追加模式操作

文件是记录的集合,或者是硬盘上的一个位置,数据永久存储在其中。

文件的必要性

  • 当程序终止时,整个数据将丢失。

  • 存储在文件中会保留数据,即使程序终止也是如此。

  • 如果要输入大量数据,通常需要花费大量时间才能全部输入。

  • 我们可以使用很少的命令轻松访问文件的内容。

  • 您可以轻松地将数据从一台计算机移动到另一台计算机,而无需更改。

  • 通过使用 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新华

感谢打赏,我会继续努力原创。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值