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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

新华

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

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

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

打赏作者

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

抵扣说明:

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

余额充值