, .
ifstream .
ofstream .
fstream , , .
C++ <iostream> <fstream>.
++ / , / . ++ <iostream.h>. ++, , .5.
5. , ++.
cin | - |
cout | - |
cerr | - |
clog | cerr - |
:
1. ofstream.
2. open.
3. cout.
4. .
:
1. ifstream.
2. open.
3. cin , .
4. .
, ofstream.,
ofstream F;F .
:
F.open("file", mode);F , ofstream;
file ;
mode .
(. .6).
6.
ios::in | , ifstream |
ios::out | , ofstream |
ios::app | |
ios::ate | |
ios::trunc | , ios::out |
ios::nocreate | , |
ios::noreplace | |
ios::binary |
mode , :
ios::in ifstream,
|
|
ios::out ofstream.
( ) F 1 (true), 0 (false). .
, , , 0:
if (!ofs){ cout << " \n"; }is_open(). 1, . ,
if (!ofs.is_open()) cout << " \n";
:
ofstream F;F.open("abc.txt", ios::out);
, ios::out ofstream
ofstream F;F.open("abc.txt");.
ofstream F("abc.txt", ios::out);
, , . ( ), ios :: app.
, , , cout .
, F a, :
F << a;G b, c d :
G << b << c << d;. , ,
ios::eof(),int eof();.
0, , 1 .
. :
F.close;F .
1. .
#include "stdafx.h"#include <iostream>using namespace std;#include <fstream>int _tmain(int argc, _TCHAR* argv[]){ int n = 50; char str[20]; // ofstream ofs("Test.txt"); // if (!ofs) cout << " .\n"; else { ofs << "Hello!\n" << n; // ofs.close(); } // ifstream file("Test.txt"); // if (!file) cout << " .\n"; else { file >> str >> n; cout << str << "\n" << n; // file.close(); } system("pause"); return 0;}
++ , , () .
2.
#include <iostream.h>
#include <fstream.h> // ofstream
#include <stdlib.h> // exit
int main()
{ char sim;
// ,
|
|
ofstream myfile("d:\oop\myfile.txt",ios::out);
if(!myfile)
{
cerr<<" myfile.txt"<<endl;
exit(1);
}
for(int i=1;i<10;i++){
cout<<" "<<endl;
cin>>sim;
myfile.put(sim); }
myfile<<endl;
return 0;
}
3.
#include <iostream.h>
//#include <fstream.h> // ofstream
#include <fstream.h>
#include <stdlib.h> // exit
int main()
{ char sim;
ifstream myfile("d:\oop\myfile.txt",ios::in);
if(!myfile)
{
cerr<<" myfile.txt"<<endl;
exit(1);
}
int nsim=0, kolstr=0;
while (myfile.get(sim)){
if (sim==char("\n"))
kolstr++;
else
nsim++;
cout.put(sim); }
cout<<endl<<endl<<"kolstr="<<kolstr<<" "<<"nsim="<<nsim<<endl;
cin>>nsim;
return 0;
}
4.
#include <iostream.h>
#include <fstream.h> // ofstream
#include <stdlib.h> // exit
int main()
{ char sim;
ofstream myfile("d:\oop\myfile.txt",ios::in); //
//
if(!myfile)
{
cerr<<" myfile.txt"<<endl;
exit(1);
}
for(int i=1;i<10;i++){........................}
cout<<" "<<endl;
cin>>sim;
myfile.put(sim); }
myfile<<endl;
return 0;
}
5.
#include <iostream.h>
#include <fstream.h> // ofstream
#include <stdlib.h> // exit
#define size 40
int main()
{ char sim,*filename;
cout<<" d:\oop\myfile.txt \n";
filename=new char(size);
cin.getline(filename,size);
ofstream myfile(filename,ios::out);
if(!myfile)
{
cerr<<" myfile.txt"<<endl;
cin>>sim;
exit(1);
}
for(int i=1;i<10;i++){.......... }
cout<<" "<<endl;
cin>>sim;
myfile.put(sim); }
myfile<<endl;
delete[]filename;
return 0;
}