如何用另一个/ c ++代码替换一行

时间:2012-01-13 13:21:26

标签: c++ linux file-io

我正在研究ubuntu。我有一个名为test.txt的文件。我想用另一条线替换第二条线。我怎样才能做到这一点?我不想创建新文件并删除第一个文件。

我想指定新行的长度与ond的长度相同

4 个答案:

答案 0 :(得分:1)

如果文件足够小,您可以将其读入内存,对内存中的副本进行任何修改,如果退出则进行写入。

根据要求修改代码:

// A vector to store all lines
std::vector<std::string> lines;

// The input file
std::ifstream is("test.txt")

// Get all lines into the vector
std::string line;
while (std::getline(is, line))
    lines.push_back(line);

// Close the input file
is.close();

// All of the file is now in memory, each line a single entry in the vector
// "lines". The items in the vector can now be modified as you please.

// Replace the second line with something else
lines[1] = "Something else";

// Open output file
std::ofstream os("test.txt");

// Write all lines to the file
for(const auto& l : lines)
    os << l << '\n';

// All done, close output file
os.close();

答案 1 :(得分:1)

尝试类似:

#include <fstream>
#include <string>

int main() {
    const int lineToReplace = 14;
    std::fstream file("myfile.txt", std::ios::in | std::ios::out);
    char line[255];
    for (int i=0; i<lineToReplace-1; ++i) 
        file.getline(line, 255); // This already skips the newline
    file.tellg();
    file << "Your contents here" << std::endl;
    file.close();
    return 0;
}

请注意line最多可以容纳254个字节(加上空终止符),因此如果您的行占用的数量超过了这个数字,请相应调整。

答案 2 :(得分:0)

这是Python,但它更具可读性和简洁性:

f = open('text.txt', 'w+') # open for read/write
g = tempfile.TemporaryFile('w+') # temp file to build replacement data
g.write(next(f)) # add the first line
next(f) # discard the second line
g.write(second_line) # add this one instead
g.writelines(f) # copy the rest of the file
f.seek(0) # go back to the start
g.seek(0) # start of the tempfile
f.writelines(g) # copy the file data over
f.truncate() # drop the rest of the file

您也可以使用shutil.copyfileobj代替writelines来阻止文件之间的复制。

答案 3 :(得分:0)

这是我如何做到的,没有对行长度的硬性限制:

#include <fstream>
#include <string>

using namespace std;

int main()
{
    fstream file("test.txt",std::ios::in|std::ios::out);
    string line;
    string line_new="LINE2";

    // Skip the first line, file pointer points to beginning of second line now.
    getline(file,line);

    fstream::pos_type pos=file.tellg();

    // Read the second line.
    getline(file,line);

    if (line.length()==line_new.length()) {
        // Go back to start of second line and replace it.
        file.seekp(pos);
        file << line_new;
    }

    return 0;
}