文件操作集合(一)

文件的打开及创建

#include<stdio.h>
#define INFO(a) printf("信息:");printf(a);printf("\n"); //预处理命令:头文件包含和宏定义 
#define ERROR(a) printf("错误:");printf(a);printf("\n");
int main()
{
 FILE *fp=NULL;     //定义文件指针 
 fp=fopen("D:\\test.txt","rt"); //以只读方式打开文本文件 
 if(fp==NULL)     //判断文件打开是否成功
 {
  ERROR("文件text.test打开错误");
  fp=fopen("D:\\test.txt","wt"); //新建文件
  if(fp==NULL)
  {
   ERROR("新建文件text.test错误"); 
   } 
  else
  {
   INFO("新建文件text.test成功"); 
   } 
  } 
  else
  {
   INFO("成功,新建文件test.txt完成"); 
   } 
 } 

文件的关闭

#include<stdio.h>
#define INFO(a) printf("信息:");printf(a);printf("\n"); //预处理命令:头文件包含和宏定义 
#define ERROR(a) printf("错误:");printf(a);printf("\n");
int main()
{
 int i=1;      //定义变量i,接受fclose函数的返回值 
 FILE *fp=NULL;     //定义文件指针fp
 fp=fopen("D:\\hellofriends.txt","rt");
 if(fp==NULL)
   {
     ERROR("文件hellofriends.test打开失败"); 
    } 
   else
   {
     INFO("成功,文件hellofriends.test打开完成"); 
    } 
  i=fclose(fp);			//关闭文件
 if(i==0)
 {
  INFO("文件关闭成功"); 
  } 
 else
 {
  ERROR("文件关闭失败"); 
  } 
}

文件的读写

  1. 字符处理函数fgetc和fputc
#include<stdio.h>
#define INFO(a) printf("信息:");printf(a);printf("\n"); //预处理命令:头文件包含和宏定义 
#define ERROR(a) printf("错误:");printf(a);printf("\n");
int main()
{
 int i=1;
 char c;      
 FILE *fp=NULL;     //定义文件指针fp
 fp=fopen("D:\\C_language\\helloall.txt","rt");
 if(fp==NULL)
   {
     ERROR("文件helloall.test打开失败"); 
     return;      //结束程序 
    } 
   else
   {
     INFO("成功,文件helloall.test打开完成"); 
    } 
  c=fgetc(fp);
  while(c!=EOF)
  {
   putchar(c);   //打印字符
  c=fgetc(fp); 
 }
 putchar('\n');   
 i=fclose(fp);    //关闭文件
 if(i==0)
 {
  INFO("文件关闭成功"); 
  } 
 else
 {
  ERROR("文件关闭失败"); 
  } 
}
//注意文件打开的路径:每层路径的嵌入应使用双斜杠"\\"表示
原创文章 326 获赞 309 访问量 3万+

猜你喜欢

转载自blog.csdn.net/huangziguang/article/details/106123401