简体   繁体   English

在文件开头添加文本和行 (C++)

[英]Adding text and lines to the beginning of a file (C++)

I'd like to be able to add lines to the beginning of a file.我希望能够在文件的开头添加行。

This program I am writing will take information from a user, and prep it to write to a file.我正在编写的这个程序将从用户那里获取信息,并准备将其写入文件。 That file, then, will be a diff that was already generated, and what is being added to the beginning is descriptors and tags that make it compatible with Debian's DEP3 Patch tagging system.然后,该文件将是一个已经生成的差异,并且添加到开头的是描述符和标签,使其与 Debian 的 DEP3 补丁标记系统兼容。

This needs to be cross-platform, so it needs to work in GNU C++ (Linux) and Microsoft C++ (and whatever Mac comes with)这需要是跨平台的,所以它需要在 GNU C++ (Linux) 和 Microsoft C++(以及任何 Mac 自带的)中工作

(Related Threads elsewhere: http://ubuntuforums.org/showthread.php?t=2006605 ) (其他地方的相关主题: http : //ubuntuforums.org/showthread.php?t=2006605

Seetrent.josephsen's answer: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.) (这不是唯一的方法,但鉴于文件不是太大,它可能是最好的。)

You can achieve such by using std::ifstream for the input file and std::ofstream for the output file.您可以通过对输入文件使用std::ifstream并为输出文件使用std::ofstream来实现这一点。 Afterwards you can use std::remove and std::rename to replace your old file:之后,您可以使用std::removestd::rename替换旧文件:

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

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

    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;
}

Another approach which doesn't use remove or rename uses a std::stringstream :另一种不使用removerename使用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;
}

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

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