zoukankan      html  css  js  c++  java
  • 文件的输入与输出

    IO库类型和头文件

    1.iostream istream,ostream,iostream

    2.fstream  ifstram,ofstream,fstream

    3.sstream istringstream,ostringstream,stringstream

    IO对象无拷贝和复制

    fstream fstrm;//创建一个未绑定的文件流

    fstream fstrm(s);//创建一个fstream,并打开文件名为s的文件

    fstream fstrm(s,mode);//以指定模式打开文件

    fstrm.open(s);//打开名为s的文件绑定到fstrm上

    fstrm.close();//关闭文件

    fstrm.is_open();//返回一个booL值,指出文件是否打开

    文件操作:

     1 vector<string >  lines;
     2 ifstream in("new2.txt");
     3 string word;
     4 while (in>>word) {
     5     lines.push_back(word);
     6 }
     7 for (auto w : lines) {
     8     cout << w <<endl;
     9 }
    10 in.close();

    //文件模式 

    in,以读方式打开 ,只能对ifstream或fstream对象设定in

    out,以写方式打开,只能对ofstream或fstream对象设定out,以out模式打开会丢失文件数据

    app,每次操作前定位到文件末尾

    ate,打开文件后定位到文件末尾

    trunc,截断文件,必须设定out后设定

    binary;//以二进制方式进行IO

    ofstream out("new2.txt", ofstream::out | ofstream::trunc);

    为保留文件需要同时显式的指定app模式

    ofstream f("directory.txt", fstream::out);//没有则创建
        char s[]= "zheng 
    wang 
    li 
    zhou 
     ";//斜杠可换行
        f.write(s,sizeof(s)-1);//写数据,第二个参数是字符串的大小
        f.close();
        ifstream in1("directory.txt");
        try {
        
            if (in1) cout << "open file success!" << endl;
            else {
                throw runtime_error("Invalid Filename!");
            }
        }
        catch (runtime_error err) {
        
            cout << err.what() << "
    Try again ? Enter y or n" << endl;
            char c;
            cin >> c;
            if (!cin || c == 'n') {
            
                exit(0);
            }
        }
        string line,word1;
        vector<PersonInfo > people;
        while (getline(in1, line)) {
            PersonInfo info;
            istringstream record(line);
            record >>info.name;
            while (record >> word) {
            
                info.phones.push_back(word);
    
            }
            people.push_back(info);
    
        }
    
        //throw表达式表所遇到的无法处理的问题
        //try以关键子开始,以一个或多个catch语句结束,处理异常*/

    IO库类型和头文件//iostream istream,ostream,iostream//fstream  ifstram,ofstream,fstream//sstream istringstream,ostringstream,stringstream//IO对象无拷贝和复制IO库类型和头文件//iostream istream,ostream,iostream//fstream  ifstram,ofstream,fstream//sstream istringstream,ostringstream,stringstream//IO对象无拷贝和复制

  • 相关阅读:
    三大主流负载均衡软件对比(LVS+Nginx+HAproxy)
    nginx 提示the "ssl" directive is deprecated, use the "listen ... ssl" directive instead
    centos安装nginx并配置SSL证书
    hadoop创建目录文件失败
    The server time zone value 'EDT' is unrecognized or represents more than one time zone.
    脚本启动SpringBoot(jar)
    centos做免密登录
    数据库远程连接配置
    Bash 快捷键
    TCP三次握手四次断开
  • 原文地址:https://www.cnblogs.com/bingzzzZZZ/p/8434176.html
Copyright © 2011-2022 走看看