C++常用代码案例

目录

目录

1、读取market.txt配置文件,取出其中逗号分割的字符串,并输出到新的文件中。

2、从内存中写输出到文件中。


 

1、读取market.txt配置文件,取出其中逗号分割的字符串,并输出到新的文件中。

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <vector>

using namespace std;

//分割字符串, s为原始字符串,v为分割后的字符串,c为分隔符
void splitString(string& s, std::vector<std::string>&v, const string& c);

int main()
{
//    ifstream ifs;
//    ifs.open("market.txt");
    ifstream ifs("market.txt");
    if(!ifs.is_open())
    {
        cerr << "open file failed" << endl;
        exit(-1);
    }

    ofstream ofs("out.txt");
    if(!ofs.is_open())
    {
        cerr << "create file failed" << endl;
        exit(-1);
    }

    string str;
    string c = ",";
    
    while(getline(ifs, str))
    {
        vector<string> market_code;
        splitString(str, market_code, c);
        ofs << market_code[0] << " " << market_code[1] << endl;
        //cout << str << endl;
    }
    ifs.close();
    ofs.close();

return 0;
}

void splitString(string& s, std::vector<std::string>&v, const string& c)
{
        //处理每一行后面的“\r\n”
        size_t n = s.find_last_not_of("\r\n");
        if(n != string::npos)
        {
            s.erase(n+1, s.size() -n);
        }
        n = s.find_first_not_of("\r\n");
        if(n != string::npos)
        {
            s.erase(0, n);
        }

        string::size_type pos1, pos2;
        pos2 = s.find(c);
        pos1 = 0;
        while(string::npos != pos2)
        {
            v.push_back(s.substr(pos1, pos2-pos1));

            pos1 = pos2 + c.size();
            pos2 = s.find(c, pos1);
        }
        if(pos1 != s.length())
        {
            v.push_back(s.substr(pos1));
        }
}

//market.txt
2,000001
1,600519
2,000002

2、从内存中读数据写入到文件中。

 

FILE *outfile;
outfile = fopen("binR.dat, "wb");

fwrite(fileBuf + buf_cursor, sizeof(char), msg_length, outfile);

fclose(outfile);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值