简体   繁体   English

如何使用 C++ 在文件中跳转一行

[英]How to jump a line in a file using C++

I want to increase the second line in my file, but I can't.我想在我的文件中增加第二行,但我不能。 How can I do it?我该怎么做?

Here is my file content这是我的文件内容

0
0

I want to increase the second '0' by 1. Here is my code:我想将第二个“0”增加 1。这是我的代码:

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

int main()
{
    std::fstream file;
    file.open("file1.txt");

    std::string line;
    getline(file, line);
    getline(file, line);
    int a = std::stoi(line);
    ++a;
    line = std::to_string(a);
    file.close();

    file.open("file1.txt");
    std::string line1;
    getline(file, line1);
    getline(file, line1);
    file << line;
    file.close();
}

You are trying too hard.你太努力了。 This is the easy way这是简单的方法

int main()
{
    std::ifstream file_in("file1.txt");
    int a, b;
    file_in >> a >> b;
    file_in.close();
    ++b;
    std::ofstream file_out("file1.txt");
    file_out << a << '\n' << b << '\n';
    file_out.close();
}

Read the whole contents of the file.读取文件的全部内容。 Make the modification needed.进行必要的修改。 Write the whole contents of the file.写入文件的全部内容。

Doing partial updates (as you are trying) can be done, but it's tricky.可以进行部分更新(如您所尝试的那样),但这很棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM