且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将文本和行添加到文件的开头(C ++)

更新时间:2023-12-02 23:36:22

请参阅 trent.josephsen的答案:


您不能在磁盘上的文件开头插入数据。您需要将整个文件读入内存,在开头插入数据,然后将整个内容写回磁盘。 (这不是唯一的方法,但给定的文件不是太大,它可能是***的。)

You can't insert data at the start of a file on disk. You need to read the entire file into memory, insert data at the beginning, and write the entire thing back to disk. (This isn't the only way, but given the file isn't too large, it's probably the best.)

通过使用 std :: ifstream 作为输入文件和 std :: ofstream 输出文件。之后,您可以使用 std :: remove std :: rename 替换旧文件:

You can achieve such by using std::ifstream for the input file and std::ofstream for the output file. Afterwards you can use std::remove and std::rename to replace your old file:

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

int main(){
    std::ofstream outputFile("outputFileName");
    std::ifstream inputFile("inputFileName");
    std::string tempString;

    outputFile << "Write your lines...\n";
    outputFile << "just as you would do to std::cout ...\n";

    outputFile << inputFile.rdbuf();

    inputFile.close();
    outputFile.close();

    std::remove("inputFileName");
    std::rename("outputFileName","inputFileName");

    return 0;
}

另一种不使用 code>或 rename 使用 std :: stringstream

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

int main(){
    const std::string fileName = "outputFileName";
    std::fstream processedFile(fileName.c_str());
    std::stringstream fileData;

    fileData << "First line\n";
    fileData << "second line\n";

    fileData << processedFile.rdbuf();
    processedFile.close();

    processedFile.open(fileName.c_str(), std::fstream::out | std::fstream::trunc); 
    processedFile << fileData.rdbuf();

    return 0;
}