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
- C语言指针-----指针与文件
- C语言文件指针
- c语言与指针
- 【C语言】文件指针与文件位置指针,位置指针相关操作库函数
- 【C语言】文件指针与文件位置指针,位置指针相关操作库函数
- 【C语言】文件指针与文件位置指针,位置指针相关操作库函数
- C语言:指针数组与数组指针
- C语言--行指针与列指针
- C语言指针数组与数组指针
- C语言指针-----指针与变量
- C语言指针-----指针与数组
- C语言指针-----指针与函数
- C语言指针-----指针与结构体
- C语言指针-----指针与字符串
- C语言函数指针与指针函数
- C语言,函数指针与指针函数
- C语言指针越界与野指针
- C语言指针详解-----数组与指针
- python中if __name__ == '__main__': 的解析
- Android Studio 配置 JDK1.8 使用Lambda表达式
- Oracle中dual虚拟表
- <LeetCode OJ> 27. Remove Element
- android studio中如何设置注释模板
- C语言指针-----指针与文件
- Oracle中的事务
- Codeforces 607A Chain Reaction 【二分 + dp】
- Ubuntu 15.10创建桌面快捷方式、启动器
- Intersection of Two Linked Lists 判断两个单链表里边有没有重叠,返回重叠的第一个节点
- 在CentOS 6.6 64bit上安装vim智能补全插件YouCompleteMe
- JDBC部分回顾注意点
- 第九章(1)-事件处理机制-学习笔记
- sslsocket双向验证通信及单向验证通信