C++读取txt中某指定内容并保存到另外一个txt中?
高洛峰
高洛峰 2016-11-19 14:19:01
0
4
958

大家好,有一个txt文件,有n多行下面格式的信息。

05-03-2016 11:03:15.0341 "GOOGLE" 124.60

要求是比如说公司是google,就把所有叫google的保存到一个txt。另一个公司叫apple,那我就另保存一个文档。现在读取后不知道怎么存,怎么选。希望大家可以帮助!!谢谢!!!


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
学霸
#include <iostream>
#include <fstream>
#include <map>
#include <string>

using std::string;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::map;

int main(int argc, char const *argv[])
{
    const char *input_file = "in.txt";
    ifstream ifs(input_file);;
    if (!ifs)
    {
        cout << "input_file not exist" << endl;
        return -1;
    }

    string date, time, cname, num;
    map<string, ofstream> ofs_map;

    while (ifs >> date >> time >> cname >> num)
    {
        if (ofs_map.find(cname) == ofs_map.end()) //logn
        {
            ofstream out(cname, ofstream::app);
            ofs_map.insert(std::make_pair(cname, out));
        }
        else
            ofs_map.at(cname) << date << " " << time << " " << cname << " " << num << endl;
    }

    ifs.close();
    for (auto i : ofs_map)
    {
        i.second.close();
    }

    return 0;


三叔

这种问题用Python解决吧!两行代码的事情,awk,sed都很快。

#include <fstream>
#include "myspilt" // 这个函数自己找
using namespace std;

int main()
{
    ifstream in(read_path);
    ofstream out(write_path);
    while(!in.eof())
    {
        string str;
        getline(in, str);
        string s = string.spilt(' ')[2];
        out(s);
    }
    
    return 0;
}


学霸
#include <fstream>

ifstream in(read_path);
ofstream out(write_path);
while (!in.eof()) 
{
out.put(in.get());
}
in.close();
out.close();


三叔

char lines[1024];
FILE *ptr_read_file = fopen(read_path, "rt");
FILE *ptr_write_file = fopen(write_path, "wt");

fgets(lines, 1024, ptr_read_file);

fputs(lines, 1024, ptr_write_file);

fclose(ptr_read_file);ptr_read_file = NULL;

fclose(ptr_write_file);ptr_write_file = NULL;


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!