美文网首页
C++ 简单文件读写

C++ 简单文件读写

作者: XY9264 | 来源:发表于2019-04-28 10:26 被阅读0次

需要包括库文件

#include <fstream>

(1) ofstream:写操作,输出文件类;
(2) ifstream:读操作,输入文件类;
(3) fstream:可同时读写的文件类。
一般使用ofstream 和ifstream更加清楚明了

 ifstream fin("input.txt");  
 ofstream fout("input.txt");  
if (! fin.is_open())    { cout << "Error opening file"; exit (1); }   //判断是否open成功
f (! out.is_open())    { cout << "Error opening file"; exit (1); }   //判断是否open成功

“>>” 从文件读入数据, “<<”数据写入文件


使用getline 读入一行数据到字符数组:

char buffer[256];  
while (fin.getline (buffer,256) ) 
{  //或者! fin.eof()  
      cout << buffer << endl; 
 }

使用geline读入一行数据到字符串:

string s;
while( getline(fin,s) ){
      cout << "Read from file: " << s << endl; 
}

使用>>逐词读取,按空格区分

string s;  
while( fin >> s ) {
cout << "Read from file: " << s << endl;  
}

使用get()读取一个字符


char c;
while(!fin.eof()){
c = fin.get()
cout<<c<<endl;
}

使用<<写文件

if (fout.is_open()) {  
fout<< "This is a line.\n";  
fout<< "This is another line.\n";  
fout.close();  
}  

相关文章

  • C++ 简单文件读写

    需要包括库文件 (1) ofstream:写操作,输出文件类;(2) ifstream:读操作...

  • 2019-03-06 C++二进制文件结构体读取问题

    C与C++的二进制文件读写 参考下面的文章,C/C++读写文本文件、二进制文件 https://blog.csdn...

  • 文件读写总结

    1. C++文件读写详解 1.1. 文件读写操作 使用方式 1.1.1. 打开文件 文件操作通过成员函数open(...

  • c++ 积累

    c++读写文件 写文件 读文件 sudo ln -s /usr/local/cuda-9.1 /usr/local...

  • c++文件读写

    ifstream ifs;连续读写文件时: ifstream 是有状态的对象,一个 ifstream 操作完后一般...

  • C++文件读写

    1、 定义数据流对象指针 对文件进行读写操作首先必须要定义一个数据流对象指针,数据流对象指针有三种类型,它们分别是...

  • c++ 读写文件

    写文件文本 读文件文本 读写二进制文件

  • c++文件读写

    c++的文件读写,其实要导入一个新的头文件,差不多每实现一个新的功能就要导入一个新的头文件,从这个角度来看,还是现...

  • C++ 读写文件

    文件操作 文本文件 写文件 读文件 接下来我们看下用string来进行读文件 第四种是每个字符进行操作

  • C++文件读写

    欲对文件进行读写操作,首先得包含fstream[https://www.jianshu.com/writer]头文...

网友评论

      本文标题:C++ 简单文件读写

      本文链接:https://www.haomeiwen.com/subject/tbornqtx.html