【问题标题】:Replace line in txt file c++替换txt文件c ++中的行
【发布时间】:2015-01-23 10:19:18
【问题描述】:

我只是想知道,因为我在 accounts.txt

中有一个包含 STATUS:USERID:PASSWORD 的文本文件

示例如下:

打开:bob:askmehere:

打开:john:askmethere:

LOCK:rob:robmypurse:

我的主目录中有一个用户输入,因为这样的用户可以登录 3 次,否则状态将从 OPEN 变为 LOCK

john

3 次尝试后的示例

之前:

打开:bob:askmehere:

打开:john:askmethere:

LOCK:rob:robmypurse:

之后:

打开:bob:askmehere:

LOCK:john:askmethere:

LOCK:rob:robmypurse:

我所做的是:

void lockUser(Accounts& in){
// Accounts class consist 3 attributes (string userid, string pass, status)

ofstream oFile;
fstream iFile;
string openFile="accounts.txt";
string status, userid, garbage;
Accounts toupdate;

oFile.open(openFile);
iFile.open(openFile);

    while(!iFile.eof()){

        getline(iFile, status, ':');
        getline(iFile, userid, ':');
        getline(iFile, garbage, '\n');


        if(userid == in.getUserId()){

            toupdate.setUserId(in.getuserId());
            toupdate.setPassword(in.getPassword());
            toupdate.setStatus("LOCK");
            break;
    }

    //here i should update the account.txt how do i do that?
    ofile.open(openFile);

    ofile<<toupdate.getStatus()<<":"<<toupdate.getUserId()":"<<toupdate.getPassword()<<":"<<endl;
}

【问题讨论】:

  • 要么读入整个文件,并在内存中替换合适的单词,要么将文件中的光标放到正确的位置,然后替换那里的单词。
  • 不要这样做 while (!iFile.eof()) 因为除非你小心,否则它不会像你期望的那样工作。原因是eofbit 标志直到您尝试从文件之外读取时才设置,从而导致循环迭代一次到多次。相反,例如while (std::getline(...))

标签: c++ fstream ostream


【解决方案1】:

有两种常用的方法来替换或修改文件。第一种也是“经典”的方式是逐行读取文件,检查需要修改的行,然后写入 临时 文件。当您到达输入文件的末尾时,您将其关闭,并将临时文件重命名为输入文件。

另一种常见的方法是当文件比较小,或者你有很多内存时,把它全部读入内存,做需要的修改,然后把内存的内容写到文件中。 如何在内存中存储它可以是不同的,比如一个包含文件中行的向量,或者一个包含文件中所有字符而不分离的向量(或其他缓冲区)。

您的实现存在缺陷,因为您在循环内打开了输出文件(与输入文件相同)。第一个问题是,如果您已经打开文件进行读取,操作系统可能不允许您打开文件进行写入,并且由于您不检查打开文件的失败,您不会知道这一点。另一个问题是如果操作系统允许,那么您对open 的调用将截断现有文件,导致您丢失除第一行之外的所有文件。


简单的伪代码来解释

std::ifstream input_file("your_file");
std::vector<std::string> lines;
std::string input;
while (std::getline(input_file, input))
    lines.push_back(input);

for (auto& line : lines)
{
    if (line_needs_to_be_modified(line))
        modify_line_as_needed(line);
}

input_file.close();

std::ofstream output_file("your_file");
for (auto const& line : lines)
    output_file << line << '\n';

【讨论】:

  • 那我该怎么做呢? @Joachim Pileborg
  • @isme 用一些简单的伪代码更新了我的答案。
【解决方案2】:

使用 ReadLine 并找到您要替换的行,并使用 replace 替换您要替换的内容。例如写:

string Example = "Text to find";
openFile="C:\\accounts.txt"; // the path of the file
ReadFile(openFile, Example);

#include <fstream>
#include <iostream>
#include <string>

int main() {
    ifstream openFile;
    string ExampleText = BOB;
    openFile("accounts.txt");
    openFile >> ExampleText;
    openFile.replace(Example, "Hello");
}

【讨论】:

  • 你在这里使用什么 C++ 魔法? ifstream 根本没有成员函数 replace
猜你喜欢
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 2016-09-04
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多