簡體   English   中英

替換文件中間的文本

[英]replace text in middle of the file

我有.txt文件,有.txt行:

username1:123456789:etc:etc:etc:etc
username2:1234:etc:etc:etc:etc
username3:123456:etc:etc:etc:etc
username4:1234567:etc:etc:etc:etc

username1 - 用戶名; 123456789 - 密碼; 等等 - 更多的文字。

我有代碼來讀取文件並找到我需要的username所在的行。 還有代碼更改密碼,但如果新密碼比舊密碼長,則會出現問題,如下所示:

username3:11111111111tc:etc:etc:etc

如果新密碼較短,則它看起來像:

username1:111111789:etc:etc:etc:etc

我有新密碼的長度,但是如何獲得舊密碼的長度並正確替換它?

我的代碼

include<iostream>
#include<fstream>
#include <cstring>

using namespace std;

int main() {
    int i=0;
    bool found = false;
    string line, username;
    char newpass[255] = "555555555555555";
    long length, plen;


    cout<<"Insert username: ";
    cin>>username;
    username+=":";
    fstream changeLINE("/.../testaDoc.txt");

    if (!changeLINE) {
        cout << "Can't find the file or directory!" << endl;
    }
    else

        while (getline(changeLINE, line) && !found) {
            i++;

            if (line.find(username) != string::npos) {
                length = changeLINE.tellg();
                changeLINE.seekg((length - line.length()) + username.length() - 1);
                changeLINE.write("", strlen(newpass));
                cout << line << " line " << i << endl;
                found = true;
            }
        }

    if (!found)
        cout << "User with username = " << username << " NOT FOUND!";

    changeLINE.close();

}

我在 Linux 上工作,用 C++ 編寫。

編輯

也許有辦法在文本中添加字符串,但不能替換它,也可以通過不替換來擦除字符串? 然后我可以讀取舊密碼的長度與新密碼進行比較並刪除/添加字符串中的字母以正確替換它。

除非您要替換的行與新行的長度相同,否則您需要一種不同的策略-

這是您可以使用的策略:

  • 創建臨時文件
  • 將您不想更改的行直接寫入臨時文件。 你要改的那條線,你用新的那條線替換
  • 關閉這兩個文件。
  • 刪除原始文件
  • 將臨時文件重命名為原始文件名

或者您可以如評論中所述將所有行讀入內存,例如行向量,替換您想要更改的行,然后將所有行寫回文件,替換以前的內容。 如果新行比前一行短,您可以使用例如截斷文件How to truncate a file while it is open with fstream

這可以工作嗎:

std::vector<std::string> lines;
while (std::getline(changeLINE, line)) 
{
    i++;

    if (line.find(username) != std::string::npos) {            
        std::cout << line << " line " << i << std::endl;
        found = true;
        std::string newline = username + ":" + newpass +     line.substr(line.find(":", username.length() + 2)) ;
        lines.push_back(newline);
    }
    else
    {
        lines.push_back(line);
    }
}

changeLINE.close();
std::ofstream ofs;
ofs.open("/.../testaDoc.txt", std::ofstream::out | std::ofstream::trunc);

for(auto& s: lines)
    ofs << s << std::endl;

ofs.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM