C++/File/ofstream

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Accessing Data in a File

  
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}
int main(){
   vector<int> output_data( 10 );
   generate( output_data.begin(), output_data.end(), rand );
   transform( output_data.begin(), output_data.end(),output_data.begin(), bind2nd( modulus<int>(), 10 ) );
   ofstream out( "data.txt" );
   if( !out )
   {
      cout << "Couldn"t open output file\n";
      return 0;
   }
   copy( output_data.begin(), output_data.end(),ostream_iterator<int>( out, "\n" ) );
   out.close();
   ifstream in( "data.txt" );
   if( !in )
   {
      cout << "Couldn"t open input file\n";
      return 0;
   }
   vector<int> input_data( (istream_iterator<int>( in )),istream_iterator<int>() );
   in.close();
   print( output_data );
   print( input_data );
}


basic file operations

  
#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}


basic file operations: open and save

  
#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}


Connect ofstream and streambuf and operations with streambufs.

  
#include <iostream>
#include <fstream>
using namespace std;
int main(void){
   int c;
   char *filename = "test.txt";
   ofstream outfile;
   streambuf *out, *input = cin.rdbuf();
   outfile.open( filename, ios::ate | ios::app);
   if (!outfile) 
   {
      cerr << "Could not open " << filename;
      return(-1);
   }
   out = outfile.rdbuf();  
   while ( (c = input -> sbumpc() ) != EOF){
      cout << char(c);                         // Echo to screen.
      if (out -> sputc(c) == EOF)
         cerr << "Output error";
   }
}


eat the newline after the file name

  
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
   char buffer[255];    
   ofstream fout("text.txt");  
   fout << "This line written directly to the file...\n";
   cout << "Enter text for the file: ";
   cin.ignore(1,"\n");
   cin.getline(buffer,255);
   fout << buffer << "\n";
   fout.close();         
   ifstream fin("text.txt");    
   char ch;
   while (fin.get(ch))
      cout << ch;
   fin.close();
 return 0;
}


ofstream.fail() Demo

 
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
   ofstream outfile;
   outfile.open("file.dat");
   cout << "( outfile) = " << outfile << endl;
   cout << "( outfile.fail()) = " << outfile.fail() << endl;
   return 0;
}


ofstream: Use read(), write(), ios::out | ios::binary

 
#include <iostream> 
#include <fstream> 
using namespace std; 
 
int main() 
{ 
  int n[5] = {1, 2, 3, 4, 5}; 
  register int i; 
 
  ofstream out("test", ios::out | ios::binary); 
  if(!out) { 
    cout << "Cannot open file.\n"; 
    return 1; 
   } 
 
  out.write((char *) &n, sizeof n); 
 
  out.close(); 
 
  for(i = 0; i <5; i++) // clear array 
    n[i] = 0; 
 
  ifstream in("test", ios::in | ios::binary); 
  if(!in) { 
    cout << "Cannot open file.\n"; 
    return 1; 
  } 
 
  in.read((char *) &n, sizeof n); 
 
  for(i = 0; i <5; i++) // show values read from file 
    cout << n[i] << " "; 
 
  in.close(); 
 
  return 0; 
}


Output file with ofstream

 
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
  ofstream pout("test");
  if(!pout) {
    cout << "Cannot open file.\n";
    return 1;
  }
  pout << "A   444 555-4444\n";
  pout << "B   222 555-2222\n";
  pout << "Joe 333 555-1111\n";
  pout.close();
  return 0;
}


put( ) to write all characters from zero to 255 to a file called CHARS.

  
#include <iostream>
#include <fstream>
using namespace std;
   
int main()
{
  int i;
  ofstream out("CHARS", ios::out | ios::binary);
   
  if(!out) {
    cout << "Cannot open output file.\n";
    return 1;
  }
   
  // write all characters to disk
  for(i=0; i<256; i++) out.put((char) i);
   
  out.close();
  return 0;
}


reads strings entered at the keyboard and writes them to disk

  
#include <iostream>
#include <fstream>
using namespace std;
   
int main(int argc, char *argv[])
{
  if(argc!=2) {
    cout << "Usage: output <filename>\n";
    return 1;
  }
   
  ofstream out(argv[1]); // output, normal file
   
  if(!out) {
    cout << "Cannot open output file.\n";
    return 1;
  }
   
  char str[80];
  cout << "Write strings to disk. Enter ! to stop.\n";
   
  do {
    cout << ": ";
    cin >> str;
    out << str << endl;
  } while (*str != "!");
   
  out.close();
  return 0;
}


Setting the locale to German_Germany

  
#include <iostream>
#include <fstream>
#include <locale>
using namespace std;
int main()
{
  ofstream fout("test.dat");
  if(!fout) {
    cout << "Cannot open file.\n";
    return 1;
  }
  cout << "The original locale is " << fout.getloc().name();
  locale loc("German_Germany");
  fout.imbue(loc);
  cout << "The current locale is now " << fout.getloc().name();
  cout << endl;
  if(has_facet<moneypunct<char, true> >(fout.getloc())) {
    const moneypunct<char, true> &mp = use_facet<moneypunct<char, true> >(fout.getloc());
    cout << "Money symbol: " << mp.curr_symbol() << endl;
    cout << "Thousands separator: " << mp.thousands_sep() << endl;
  }
  fout.close();
  if(!fout.good()) {
    cout << "Error closing file.\n";
    return 1;
  }
  return 0;
}


Uses put() to write all characters from zero to 255 to a file

 
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
  int i;
  ofstream out("CHARS_File", ios::out | ios::binary);
  if(!out) {
    cout << "Cannot open output file.\n";
    return 1;
  }
  // write all characters to disk
  for(i=0; i<256; i++) 
     out.put((char) i);
  out.close();
  return 0;
}


writes formatted output to a file, using

  
#include <fstream>                
  #include <iostream>  
  #include <string>  
  using namespace std;  
    
  int main(){  
     char ch = "x";  
     int j = 77;  
     double d = 6.02;  
     string str1 = "test";        
     string str2 = "this is a test";
    
     ofstream outfile("fdata.txt"); 
    
     outfile << ch                  
             << j  
             << " "                 
             << d  
             << str1  
             << " "                 
             << str2;  
     cout << "File written\n";  
     return 0;  
  }


Writes information inputted to a file

 
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
   char data[80];
   ofstream outfile;
   outfile.open("file.txt");
   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 80);
   outfile << data << endl;
   cout << "Enter your id number: "; 
   cin >> data;
   cin.ignore();
   outfile << data << endl;
   outfile.close();
   return 0;
}