美文网首页算法和数据结构
机试常用算法和题型-文件操作专题

机试常用算法和题型-文件操作专题

作者: DecadeHeart | 来源:发表于2020-04-25 16:22 被阅读0次

文件操作

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;

int main(){

  //打开文件,清空内容,重新写入,ofstream::out指示以写模式打开
  ofstream out1("D\\abc.txt",ofstream::out);
  string s;
  while(getline(cin,s)){
    out1<<s<<endl;
  }
  out1.close();
  
  //打开文件,向文件追加内容
  //ofstream::out指示以写模式打开,ofstream::app指示写操作前定位到文件末尾
  ofstream out2("D:\\abc.txt",ofstream::out|ofstream::app);
  while(getline(cin,s)){
    out2<<s<<endl;
  }
  out2.close();
  
  //读取文件
  ifstream in("D:\\abc.txt");
  vector<string> vecs;
  while(getline(in,s)){
    vecs.push_back(s);
  }
  in.close();
  return 0;
}

//输入输出流配合操作
    vector<string> inputArr;
    string inStr;
    while(cin>>inStr){
        inputArr.push_back(inStr);
        char ch=getchar();
        if(ch=='\n') break;

    }
    int len=inputArr.size();
    ofstream out1(inputArr[len-1].c_str(),ofstream::out|ofstream::app);
    for(int i=1;i<len-1;i++){
        ifstream in(inputArr[i].c_str());

        string s;
        while(getline(in,s)){

            cout<<s<<endl;
            //直接从文件里进文件里出

            //终于领会到了cout,cin流的精髓
            out1<<s<<endl;
        }
        in.close();
        out1.close();
        //app定位到文件末尾,追加内容

typedef std::string String;
//还有一种用法
void loadDirect(const String& filename)
{

    std::ifstream fp;
    fp.open(filename.c_str(), std::ios::in | std::ios::binary);
    cout<<fp.rdbuf();
    fp.clear();
    if(!fp.bad())
    {
        cout<<"打开 失败。";
    }


}

fstream f;  
f.open("1.txt", ios::in | ios::binary);  
if (!f.is_open()) // 检查文件是否成功打开  
    cout << "cannot open file." << endl;  
ios::in与ios::bianry均为int型,定义文件打开的方式。  
ios::in -- 打开文件用于读。  
ios::out -- 打开文件用于写,如果文件不存在,则新建一个;存在则清空其内容。  
ios::binary -- 以二进制bit流方式进行读写,默认是ios::text,但最好指定这种读写方式,即使要读写的是文本。因为在ios::text模式下,在写入时’\ n’字符将转换成两个字符:回车+换行(HEX: 0D 0A) 写入,读入时作逆转换,这容易引起不必要的麻烦。ios::app -- 打开文件在文件尾进行写入,即使使用了seekp改变了写入位置,仍将在文件尾写入。  
ios::ate -- 打开文件在文件尾进行写入,但seekp有效。  
读写位置的改变  
f.seekg(0, ios::beg); // 改变读入位置 g mean Get  
f.seekp(0, ios::end); // 改变写入位置 p mean Put  
第一个参数是偏移量offset(long),第二个参数是offset相对的位置,三个值:  
ios::beg -- 文件头    ios::end -- 文件尾    ios::cur -- 当前位置 

相关文章

网友评论

    本文标题:机试常用算法和题型-文件操作专题

    本文链接:https://www.haomeiwen.com/subject/akekwhtx.html