c简单的操作文件

本文介绍了使用C语言进行文件操作的基本方法,包括文件的读取、写入、追加等常见操作,以及如何利用fgetc、fputc、fgets、fputs等函数实现这些功能。此外,还介绍了二进制文件的读写操作及其注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<conio.h>
main(){
   FILE *fp;
   char c;
   if((fp=fopen("d:\\a.txt","rt"))==NULL){
       printf("\n cannot open file and exit!");
       _getch();
       exit(1);
   }
   c = fgetc(fp);
   while(c!=EOF){
      putchar(c);
      c=fgetc(fp);
   }
   fclose(fp);
   _getch();
}

上边是读取一个文件的内容。

首先定义文件指针fp  然后让fp指向对应文件  如果fopen打开文件出错,则exit, “rt”表示只读

如果成功继续,读取第一个字符,循环判断是否到达末尾(EOF),循环读取。最后别忘了关闭。  注意fgetc函数。



#include<stdio.h>
#include<conio.h>
main(){
   FILE *fp;
   char c;
   if((fp=fopen("d:\\append.txt","wt+"))==NULL){
       printf("\n cannot open file and exit!");
       _getch();
       exit(1);
   }
   scanf("input a string : \n");
   c = getchar();
   while(c!='\n'){
      fputc(c,fp);
      c = getchar();
   }
   fclose(fp);
   _getch();
}

前边一样,获取输入的第一个字符,循环判断,知道判断出最后一个字符(回车键), 每次循环把这个char   put到对应的文件指针,即写入。注意fputc函数。



#include<stdio.h>
#include<conio.h>
main(){
   FILE *fp;
   char str[11];
   if((fp=fopen("d:\\a.txt","rt"))==NULL){
       printf("\n cannot open file and exit!");
       _getch();
       exit(1);
   }
   
   fgets(str,11,fp);
   printf("\n%s\n",str);
   
   fclose(fp);
   _getch();
}

还要注意一个函数  fgets,  比如上边的fgets(str,11,fp)表示从文件指针中获取11个字符的长度,并把获取的值赋值给str。


#include<stdio.h>
#include<conio.h>
main(){
   FILE *fp;
   char ch, str[100];
   if((fp=fopen("d:\\a.txt","at+"))==NULL){
       printf("\n cannot open file and exit!");
       _getch();
       exit(1);
   }
   
   printf("input a string: \n");
   scanf("%s",str);
   fputs(str,fp);
   
   fclose(fp);
   _getch();
}

fputs就不解释了,很明了。


#include<stdio.h>
#include<conio.h>
main(){
   FILE *fp;
   char ch, str[100];
   if((fp=fopen("d:\\a.txt","wb+"))==NULL){
       printf("\n cannot open file and exit!");
       _getch();
       exit(1);
   }
   
   char write[26] = "abcdefghijklmnopqrstuvwxyz";
   fwrite(write,4,4,fp);
   
   rewind(fp);
   fread(str, 4, 4, fp);   // 在这之前需要rewind到开始 
   printf("%s \n",str);
   
   printf("operate is over \n");
      
   fclose(fp);
   _getch();
}

fread函数和fwrite函数。

fwrite代表把write的值每次4字节,连续写4次,写入到fp文件指针。

同理fread。

需要说明的是示例中的rewind函数,fwrite操作后,操作指向了文件末尾,这时候需要重新指向文件开始。否则直接读出来会是空。


最后介绍介个函数,做判断用。

1. feop(文件指针)  判断文件是否处于结束位置

2. feeror(文件指针) 检查文件读写是否出错,返回为0 表示正确

3. cleanerr(文件指针) 清楚出错标志和文件结束标志


最后,给出文件方式缩写表:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值