c++按元素编辑txt文件

标签 c++ file

我有一个 txt 文件,其中保存按以下顺序排列的信息:

Name somename
Age someAge
Address someAddress
...

我按如下元素查找此信息:

if (myfile.is_open())
{
    while (myfile >> element1)
    {
        myfile >> element2;

        if (element1 == "Name")
            _name = element2; //element2 is someName in .txt file

        if (element1 == "Age")
            _age = element2; //element2 is someAge in .txt file
        ...
    }
    myfile.close();
}

等等...

也可以使用 ofstream 以这种方式编辑 txt 文件吗?

最佳答案

"It is possible to edit the txt file this way too using ofstream?"

是的,这是可能的。只是不是立即操纵文件内容(正如您可能正在考虑的那样)。

  1. 您使用 std::ifstream 读入文件一行一行变成std::vector<std::string>变量
  2. 您使用各种 std::string 操作这些行根据需要发挥作用
  3. 您打开与 std::ofstream 相同的文件(使用std::iosbase::trunc标志打开)
  4. 你写下你所有的std::vector<std::string>输出文件的变量

作为@Jerry Coffin mentioned ,您可以考虑首先创建被操作文件的备份。如果这样做,您还可以利用操作单个记录,而无需读入整个文件(如果它真的很大,可能会导致内存问题)。

关于c++按元素编辑txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218129/

相关文章:

c++ - Mac 应用程序的文件保存位置

c++ 和 openCV 与 windows8 : VideoWriter class not opening

java - 使用外部文件的空指针异常

ios - 如何获取我的 built.io 应用程序中上传的所有文件的列表?

file - 配置 nginx 静态缓存某些 URL

c - 使用 argv 打开文件给我文件 NULL

c++ - 清理压缩电子邮件附件的解决方案

c++ - 将可变数量的参数传递给构造函数

c++ - 是否可以在 CLI 解析完成后添加 boost program_options 和参数?

c - 检索与文件指针关联的文件的名称