问题描述
我想要在文件开头添加行。
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)
(相关主题:)
推荐答案
请参阅答案:
通过使用作为输入文件和输出文件。之后,您可以使用和替换旧文件:
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 ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!