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

来源:互联网 发布:restful 接口实例java 编辑:程序博客网 时间:2024/06/16 16:40

文件在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;  }  

这里写图片描述

1 0
原创粉丝点击