将文本和行添加到文件的开头(C ++) [英] Adding text and lines to the beginning of a file (C++)

查看:564
本文介绍了将文本和行添加到文件的开头(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在文件开头添加行。

I'd like to be able to add lines to the beginning of a file.

我写的程序会从用户那里获取信息,然后准备写入文件。那个文件将是一个已经生成的diff,添加到开头的是描述符和标签,使它与Debian的DEP3 Patch标签系统兼容。

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.

这需要跨平台,所以它需要在GNU C + +(Linux)和Microsoft C + +(和任何Mac自带)

This needs to be cross-platform, so it needs to work in GNU C++ (Linux) and Microsoft C++ (and whatever Mac comes with)

(相关主题: http://ubuntuforums.org/showthread.php?t=2006605

推荐答案

请参阅 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;
}

这篇关于将文本和行添加到文件的开头(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆