zoukankan      html  css  js  c++  java
  • 6.C++ Standard Library

    The Codes:

    // 6. C++ Standard Library
    
    /********************************************
    1. Input/Output with files
    */
    
    
    // basic file operations
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () 
    {
      ofstream myfile;
      myfile.open ("example.txt"); //如无些文件,新建一个。在程序文件的同一目录下
      myfile << "Writing this to a file.
    ";
      myfile.close();
    
      return 0;
    }
    
    
    // writing on a text file
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () 
    {
      ofstream myfile("example.txt");
      if(myfile.is_open())
      {
        myfile<<"This is a line.
    ";
        myfile<<"This is another line.
    ";
        myfile.close();
      }
      else cout << "Unable to open file";
    
      return 0;
    }
    
    
    // reading a text file
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main () 
    {
      string line;
      ifstream myfile("example.txt");
      if(myfile.is_open())
      {
        while(! myfile.eof() )
        {
          getline(myfile,line);
          cout << line << endl;
        }
        myfile.close();
      }
      else cout << "Unable to open file";
    
      return 0;
    }
    
    
    
    // obtaining file size
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () 
    {
      long begin,end;
      ifstream myfile("example.txt");
      begin = myfile.tellg(); // 取得第一个光标位置
      myfile.seekg(0,ios::end);
      end = myfile.tellg(); // 取得最后一个光标位置
      myfile.close();
      cout << "size is: " << (end-begin) << " bytes.
    ";
    
      return 0;
    }
    
    
    
    
    // reading a complete binary file
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    ifstream::pos_type size;
    char * memblock;
    
    int main () 
    {
      ifstream file("example.bin",ios::in|ios::binary|ios::ate);
      if(file.is_open())
      {
        size=file.tellg();
        memblock=new char [size];
        file.seekg(0,ios::beg);
        file.read(memblock,size);
        file.close();
        
        cout << "the complete file content is in memory";
        
        delete[] memblock;
      }
      else cout << "Unable to open file";
      return 0;
    }

    TOP

  • 相关阅读:
    CentOS6.2编译安装Nginx1.2.0
    mysql之主从复制篇
    CentOS6.2编译安装PHP5.4.0
    c# 多线程 编程
    QQ空间及邮箱验证码登录的校验方式及自动登录的解决方案
    C# 动态编译、动态执行、动态调试
    在Visual C#中用ListView显示数据记录
    推荐一个免费的HTTP抓包分析工具 Fiddler Web Debugger
    C#简繁体转换方法(Microsoft.Office.Interop.Word)
    C#读取字符串类型XML
  • 原文地址:https://www.cnblogs.com/xin-le/p/4083875.html
Copyright © 2011-2022 走看看