0
点赞
收藏
分享

微信扫一扫

C语言中文件操作详解

三次方 2022-04-13 阅读 70

目录

1. 文件指针

2. 文件的打开与关闭

 3.文件的顺序读写

4. 一组函数的对比

5.文件的随机读写


1. 文件指针

说明:创建一块空间,存放一个结构体变量,结构体变量中存放了文件的相关信息;

FILE* pf; //文件指针变量

pf是一个指向FILE类型数据的指针变量,可以使pf指向某个文件的文件信息区。

2. 文件的打开与关闭

文件在读写之前应该先打开文件,在使用结束之后应该关闭文件;

ANSIC规定使用fopen函数打开文件,fclose来关闭文件;

示例:

FILE* fopen(const char* filename,const char* mode);
int fclose(FILE*stream);

示例:

//1.绝对路径的写法
fopen("C:\\Program\\data\\test.txt","r");
//2.相对路径
fopen("test.txt","r");
//..表示上一级路径
fopen("../test.txt","r");
//上上级路径
fopen("../../test.txt","r");
FILE* pf=fopen("test.txt","r");  //若是打开文件失败,会返回一个空指针
//打开成功后就会返回FILE的结构体变量的地址给pf;
if(pf=NULL)
{
    printf("%s",strerror(errno));
    return 0;
}
//打开成功
//读文件
//关闭文件
fclose(pf);
pf=NULL;
return 0;

 3.文件的顺序读写

 

示例:

int main()
{
    FILE* pfWrite=fopen("TEST.txt","w");
    if(pfWrite==NULL)
    {
        printf("%s\n",strerror(errno));
    }
    //写文件
    fputc('b',pfWrite);
    fputc('i',pfWrite);
    fputc('t',pfWrite);
    //关闭文件
    fclose(pf);
    pf=NULL;
}
int main()
 {
     FILE* pfRead=fopen("test.txt","r");
     if(pfRead==NULL)
     {
         printf("%s\n",strerror(errno));
         return 0;
     }
     //读文件
     printf("%c\n",fgetc(pfRead));  //b
     printf("%c\n",fgetc(pfRead));  //i
     printf("%c\n",fgetc(pfRead));  //t
     fclose(pfRead);
     pfRead=NULL;
     return 0;
 }
int main()
{
    char buf[1024]={0};
    FILE* pf=fopen("test.txt","r");
    if(pf=NULL)
    {
        return 0;
    }
    //读文件
    //fgets(目标,大小,来源);
    fgets(buf,1024,pf);  //假设此时pf中的内容为bit
                           //               hello;
    printf("%s",buf);   //打印结果为 bit
    fgets(buf,1024,pf);
    printf("%s",buf);  //打印结果为hello
    fclose(pf); 
    pf=NULL;
    return 0;
}
int main()
{
    FILE* pf=fopen("test.txt","w");
    if(pf=NULL)
    {
        return 0;
    }
    //写文件
    fputs("hello\n",pf); 
    fputs("world\n",pf);//此时文本中已经放入了 hello   和 world
    
}
struct s
{
    int n;
    float f;
    char arr[10];
};
int main()
{
  struct S s={100,3.14f,"bit"};
    FILE* pf=fopen("test.txt","w");
    if(pf=NULL)
    {
        return 0;
    }
    //格式化的形式写文件
    fprintf(pf,"%d %f %s",s.n,s.f,s.arr);  //fprintf()就是比printf前面多加一个输出的位置;
    fclose(pf);
    pf=NULL;
    return 0; 
}

4. 一组函数的对比

scanf/printf  是针对标准输入流/标准输出流的格式化输入/输出语句
fscanf/fprintf是针对所有输入流/所有输出流的格式化输入/输出语句
sscanf是从字符串中读取格式化的数据,sprintf是把格式化的数据输出成字符串;

5.文件的随机读写

函数原型:

int fseek(FILE* stream,long int offset,int origin)

示例:

int main()
{
    FILE* pf=fopen("test.txt","r");
    if(pf=NULL)
    {
        return 0;
    }
    //1.定位文件指针
    fseek(pf,2,SEEK_CUR);
    //2.读取文件 
    int ch=fgetc(pf);
    printf("%c"\n,ch);
    fclose(pf);
    pf=NULL;
    return 0;
}
举报

相关推荐

0 条评论