100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > c++的fstream

c++的fstream

时间:2024-01-03 15:18:47

相关推荐

c++的fstream

fstream 支持<< 和>> 操作符

C语言的文件操作

函数fopen()将一个文件和一个流关联起来。并初始化一个FILE对象,这个对象包括一个指向缓冲区的指针,文件位置指示器,以及指示错误和文件结尾情况的标识。

#include<stdio.h>#include<stdbool.h>_bool isreadwriteable(const char *filename){FILE *fp=fopen(filename,"r+");//打开一个文件用于读写if(!fp=null){fclose(fp);return true;}elsereturn false;}

C++文件操作

直接对流对象进行操作

fstream foi("........", ios::in|ios::out);

文件的写操作

包括一个

write (const *char message, int size);

#include<fiostream.h>int main(){ofstream out("filename.txt");if(out.is_open()){out<<"jion in the file.";out.close();} }

文件的读操作

#include<iostream>#include<fstream.h>#include<stdlib.h>int main(){char buffer[100];ifstream in("filename.txt");if(in.is_open()){while(in.eof()){in.getline(buffer,99);cout<<buffer<<endl;}}}

open 函数

void open(const char *filename, ios::openmode)

open mode

ios::app//以追加的模式打开文件ios::ate //文件打开后定位到文件尾,ios::app就包含此属性ios::binary//以二进制的方式打开文件,缺省的方式就是文本方式。ios::in//文件以输入方式打开(文件数据输入到内存)ios::out//文件以输出方式打开(内存数据输出到文件)ios::nocreate //不建立文件,所以文件不存在时打开失败ios::noreplace//不覆盖文件,所以打开文件时 如果文件存在 失败ios::trunc//如果文件存在,文件长度设为0

状态标识符

一些验证流的状态的成员函数(返回值为 bool 类型)

is_open()//文件是否打开bad()//读写过程中是否出错(操作对象没有打开,写入设备没有空间)fail()//读写过程中是否出错(操作对象没有打开,写入设备没有空间,格式错误)eof()//读文件达到文件末尾,返回truegood()//以上任何一个返回true,这个就返回false

获得和设置流指针

//对于所有的输入输出流都至少有一个指针,指向下一个要操作的位置ofstream put_pointifstream get_point//获取流指针的位置tellg()//获取输入流指针的位置(return long)tellp()//获取输出流指针的位置//设置指针位置seekg(long position) //设置输入流指针的位置seekp(long position)//设置输出流指针的位置

example:

#include<fstream>int main(){std::ofstream out;out.open("hello.txt");out<<"hello world";long pos=out.tellp();out.seekp(pos-3);out<<" how beautiful";out.close();}

读取文件内容

#include<iostream>#include<fstream>int main(){std::ifstream in;in.open("hello.txt");char x =in.get();//也可以是getline() 或者 >>while(in.good()){std::cout<<x;c=in.get();}in.close();}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。
相关阅读
c++ fstream用法

c++ fstream用法

2018-09-28

C++ fstream类

C++ fstream类

2021-03-18

C++之fstream

C++之fstream

2022-12-22

C++中fstream

C++中fstream

2021-08-29