Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 替换文件中部分行的正确方法是什么_C++_Fstream_Seek - Fatal编程技术网

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

C++ 替换文件中部分行的正确方法是什么,c++,fstream,seek,C++,Fstream,Seek,我有一个文件GENERIC\u MAC,其中包含我机器的一些配置,我想将MAC替换为给定的MAC(在这种情况下是硬编码的) 这条路对吗?(代码为我提供了所需的输出,但我不确定fs.tellp();+fs.seekp(位置);) 我假设(我认为这是合理的)MAC地址的长度总是相同的(例如,“XX:YY:ZZ:AA:BB:CC”) 似乎是对的。我看不到另一种在文件中移动的方法。()只要替换文本的大小与它要替换的文本的大小完全相同。唯一困扰我的是替换。你不经意地用新的MAC地址替换行尾,甚至不控制行长

我有一个文件
GENERIC\u MAC
,其中包含我机器的一些配置,我想将MAC替换为给定的MAC(在这种情况下是硬编码的)

这条路对吗?(代码为我提供了所需的输出,但我不确定
fs.tellp();
+
fs.seekp(位置);

我假设(我认为这是合理的)MAC地址的长度总是相同的(例如,
“XX:YY:ZZ:AA:BB:CC”


似乎是对的。我看不到另一种在文件中移动的方法。()只要替换文本的大小与它要替换的文本的大小完全相同。唯一困扰我的是替换。你不经意地用新的MAC地址替换行尾,甚至不控制行长。您至少应该控制剩余的部分具有预期的长度。或者,如果希望在结尾处接受额外的(可能为空)字符,请控制它至少具有预期的长度,并且只替换新MAC地址的长度。作为评论发布,因为它没有解决您问题的主要部分。
#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;
}
router interface
         address 10.10.10.10/24 

blah
         this is my MAC - XX:YY:ZZ:AA:BB:CC

...
...
...