C++ 如何在C+中写入文件的中间部分+;?
我认为这应该很简单,但我的谷歌搜索到目前为止没有帮助。。。我需要在C++中写入现有文件,但不一定要在文件的结尾。 我知道,当我只想在文件中添加文本时,我可以在调用流对象上的C++ 如何在C+中写入文件的中间部分+;?,c++,fstream,ifstream,ofstream,C++,Fstream,Ifstream,Ofstream,我认为这应该很简单,但我的谷歌搜索到目前为止没有帮助。。。我需要在C++中写入现有文件,但不一定要在文件的结尾。 我知道,当我只想在文件中添加文本时,我可以在调用流对象上的open时传递标志ios:app。但是,这只让我写到文件的最后,而不是中间 我制作了一个简短的程序来说明这个问题: #include <iostream> #include <fstream> using namespace std; int main () { string path = "
open
时传递标志ios:app
。但是,这只让我写到文件的最后,而不是中间
我制作了一个简短的程序来说明这个问题:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string path = "../test.csv";
fstream file;
file.open(path); // ios::in and ios::out by default
const int rows = 100;
for (int i = 0; i < rows; i++) {
file << i << "\n";
}
string line;
while (getline(file, line)) {
cout << "line: " << line << endl; // here I would like to append more text to certain rows
}
file.close();
}
#包括
#包括
使用名称空间std;
int main(){
字符串路径=“../test.csv”;
流文件;
file.open(path);//默认情况下ios::in和ios::out
常量int行=100;
对于(int i=0;i 文件您不能插入文件的中间。您必须将旧文件复制到新文件中,并在复制期间将中间插入的任何文件插入到新文件中。
否则,如果要覆盖现有文件中的数据/行,可以使用std::ostream::seekp()
来标识文件中的位置。可以写入结尾并交换行,直到它位于正确的位置。
这是我必须做的。
以下是之前的test.txt文件:
12345678
12345678
12345678
12345678
12345678
这是我的程序示例
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
fstream& goToLine(fstream& file, int line){
int charInLine = 10; //number of characters in each line + 2
//this file has 8 characters per line
int pos = (line-1)*charInLine;
file.seekg(pos);
file.seekp(pos);
return file;
}
fstream& swapLines(fstream& file, int firstLine, int secondLine){
string firstStr, secondStr;
goToLine(file,firstLine);
getline(file,firstStr);
goToLine(file,secondLine);
getline(file,secondStr);
goToLine(file,firstLine);
file.write(secondStr.c_str(),8); //Make sure there are 8 chars per line
goToLine(file,secondLine);
file.write(firstStr.c_str(),8);
return file;
}
int main(){
fstream file;
int numLines = 5; //number of lines in the file
//open file once to write to the end
file.open("test.txt",ios::app);
if(file.is_open()){
file<<"someText\n"; //Write your line to the end of the file.
file.close();
}
//open file again without the ios::app flag
file.open("test.txt");
if(file.is_open()){
for(int i=numLines+1;i>3;i--){ //Move someText\n to line 3
swapLines(file,i-1,i);
}
file.close();
}
return 0;
}
我希望这有帮助!基于我对操作系统的基本知识,我认为这是不可能的。
我的意思是,用当前的存储技术制作一个能够实现这种功能的操作系统并非不可能,但这样做总是会在各个部分浪费空间
但我不知道有哪种技术可以做到这一点。尽管一些基于云的数据库确实在功能上使用了这类功能(比如在文件中间插入内容),但它们是专为DBMS软件设计的,具有非常明确的目标硬件,并且它们可能还有一些定制的内核来执行这些任务。只是为了完成:您不能插入到文件的中间,但可以通过覆盖来替换相同数量的字节。要进一步完成,请参阅示例代码;basical首先,您可以使用seekp()成员函数将文件指针移动到任何位置,然后开始写入。但是,EOF之前的任何写入操作都将替换旧数据。您可能希望使用索引文件库(如)或,甚至是完整的数据库(,…)更改文件的标准方法:读取输入文件,处理,写入新的输出文件,成功后,用输出文件覆盖输入文件。有“更快”的替代方法(如ios::app),但它们并不适用于每种情况。这里不是已经问过一百万次了吗?的确,f.e。(不过,我知道这是一个反问)
12345678
12345678
someText
12345678
12345678
12345678