C++读取txt中某指定内容并保存到另外一个txt中?

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

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

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

阅读 3.3k
4 个回答

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;

#include <fstream>

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

这种问题用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 <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;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题