什么是替换文件中部分行的正确方法

时间:2018-07-19 07:32:30

标签: c++ fstream seek

我有一个文件var itemsProcessed = 0; async.forEach(categories, function(category, cb) { Audit.find({ 'category_id': category._id }, 'created_at updated_at user_Id entreprise_id nom _id category_id', function(err, auds) { category.products = []; category.count = 0; if (err) res.send(err); category.products = auds; category.count = auds.length; itemsProcessed++; if (itemsProcessed == categories.length) { cb(); } }); }, function() { res.json(categories); }); ,其中包含我的计算机的某些配置,我想将MAC替换为给定的MAC(在这种情况下为硬编码)。

这是正确的方法吗? (代码为我提供了所需的输出,但是我不确定GENERIC_MAC + fs.tellp();

我已经做出了一个假设(我认为这是合理的),即MAC地址始终具有相同的长度(例如fs.seekp(position);

"XX:YY:ZZ:AA:BB:CC"

文件看起来像这样:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char* path = "....GENERIC_MAC";
    char* MAC  = "XX:YY:ZZ:AA:BB:CC"; /* the actual code returns the MAC as char* - should I convert to string? */
    string prefix = "this is my MAC - ";
    size_t pos;
    fstream fs(path);
    string line;
    streampos position;

    cout << "START\n";

    while (std::getline(fs, line))      {
        if ((pos = line.find(prefix, 0)) == std::string::npos) {
            position = fs.tellp();
            continue;
        }
        /* replace the 00:11:22:33:44:55 MAC with this device's MAC */
        cout << "old = " << line << endl;
        line.replace(pos + prefix.length(), string::npos, MAC);
        cout << "new = " << line << endl;

        fs.seekp(position);
        fs << line << endl;
        break;
    }

    cout << "END\n";
    return 0;
}

0 个答案:

没有答案
相关问题