简介
本文主要整理了一些博主的优质内容,进行一些优质整合。(后续进行更多补充)
常见的流操作如下:
#include <fstream>
ofstream
ifstream
fstream
具体一些代码功能实现
ifstream配合getline读取文件每行数据
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string str;
ifstream ifs('test.txt');
if(!ifs)
{
cout<<'open file fail!'<<endl;
return 1;
}
while( getline(ifs,str))
{
cout<<str<<endl;
}
return 0;
}
ofstream实现对文件写入每行数据
#include <fiostream.h>
int main () {
ofstream out("test.txt");
if (out.is_open())
{
out << "This is a line.\n";
out << "This is new line.\n";
out.close();
}
return 0;
}
fstream对文件读写操作
#include<fstream.h>
void main()
{
fstream f("d:\\try.txt",ios::out);
f<<1234<<' '<<3.14<<'A'<<"How are you";
f.close();
f.open("d:\\try.txt",ios::in);
int i;
double d;
char c;
char s[20];
f>>i>>d>>c;
f.getline(s,20);
cout<<i<<endl;
cout<<d<<endl;
cout<<c<<endl;
cout<<s<<endl;
f.close();
}
ifstream和ofstream操作二进制文件
#include<fstream.h>
void main()
{
ifstream fin("C:\\1.exe",ios::nocreate|ios::binary);
if(!fin){
cout<<"File open error!\n";
return;
}
ofstream fout("C:\\2.exe",ios::binary);
char c[1024];
while(!fin.eof())
{
fin.read(c,1024);
fout.write(c,fin.gcount());
}
fin.close();
fout.close();
cout<<"Copy over!\n";
}
ifstream一次读一个字符
#include<fstream.h>
void main()
{
ifstream fin("d:\\简介.txt",ios::nocreate);
if(!fin){
cout<<"File open error!\n";
return;
}
char c;
while((c=fin.get())!=EOF)cout<<c;
fin.close();
}
ifstream读到特殊字符停止读取
include<fstream.h>
void main()
{
ifstream fin("d:\\简介.txt",ios::nocreate);
if(!fin){
cout<<"File open error!\n";
return;
}
char c[80];
while(fin.get(c,80,'\0')!=NULL)cout<<c;
fin.close();
}
上面主要摘自: 博主wode0239
|