C语言指针-----指针与文件

文件在C语言里被定义成了结构体,这个结构体包含了文件的一些信息

FILE *fptr;

关于FILE这个结构体定义在stdio.h文件中,这个结构体定义如下:

struct _iobuf {
        char *_ptr;        //文件输入的下一个位置
        int   _cnt;        //当前缓冲区的相对位置
        char *_base;       //文件的起始位置
        int   _flag;       //文件标志
        int   _file;       //文件的有效性验证 
        int   _charbuf;    //检查缓冲区状况,如果无缓冲区则不读取
        int   _bufsiz;     //文件的大小 
        char *_tmpfname;   //临时文件名
        };
typedef struct _iobuf FILE;

在C语言中,文件的操作都是通过库来完成的,最基本的就是打开文件和关闭文件函数。

FILE* fopen(const char*, const char*);//fopen函数原型
int fclose(FILE*);//fclose函数原型
  ┌──┬────┬───────┬────────┐
  │type│读写性  │文本/2进制文件│建新/打开旧文件 │
  ├──┼────┼───────┼────────┤
  │r   │读      │文本          │打开旧的文件    │
  │w   │写      │文本          │建新文件        │
  │a   │添加    │文本          │有就打开无则建新│
  │r+  │读/写   │不限制        │打开            │
  │w+  │读/写   │不限制        │建新文件        │
  │a+  │读/添加 │不限制        │有就打开无则建新│
  └──┴────┴───────┴────────┘

常见的读写函数:
1、字符读写函数 : fgetc和fputc
2、字符串读写函数:fgets和fputs
3、数据块读写函数:fread和fwrite
4、格式化读写函数:fscanf和fprinf

#include<stdio.h>

int main(void){

    char str[10];
    FILE *fptr=fopen("test.txt","rw");
    if(fptr==NULL){
        printf("there is not the file!\n");
        return 1;
    }
    else{
        printf("this is good!\n");
    }
    fputs("Iloveyou",fptr);
    fputs("Iloveyou",fptr);
    rewind(fptr);
    printf("---------");
    if(fgets(str,4,fptr)==NULL){
        printf("fgets is failed");
        return 1;   
    }
    printf(str);
    printf("---------\n");

    fclose(fptr);
}

代码二:

#include<stdio.h>
#include<string.h>
int main()  
{  
    FILE *stream;  
    char string[]="This is a test";  
    char msg[20];  
    /*w+打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。*/  
    stream=fopen("abc.txt","w+"); /*open a file for update*/  
    fwrite(string,strlen(string),1,stream); /*write a string into the file*/  
    fseek(stream,0,SEEK_SET);  /*seek to the start of the file*/  
    fgets(msg,strlen(string)+1,stream);  
    printf("%s",msg);  
    fclose(stream);  
    return 0;  
}  

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值