• 文件的输入与输出


    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对象无拷贝和复制

  • 相关阅读:
    【校招面试 之 C/C++】第23题 C++ STL(五)之Set
    Cannot create an instance of OLE DB provider “OraOLEDB.Oracle” for linked server "xxxxxxx".
    Redhat Linux安装JDK 1.7
    ORA-10635: Invalid segment or tablespace type
    Symantec Backup Exec 2012 Agent for Linux 卸载
    Symantec Backup Exec 2012 Agent For Linux安装
    You must use the Role Management Tool to install or configure Microsoft .NET Framework 3.5 SP1
    YourSQLDba介绍
    PL/SQL重新编译包无反应
    MS SQL 监控数据/日志文件增长
  • 原文地址:https://www.cnblogs.com/bingzzzZZZ/p/8434176.html
Copyright © 2020-2023  润新知