保持文本文件从擦除在一个函数,但保持能力写到它?c++
Keep a text file from wiping in a function but keep ability to write to it? C++
我有一个函数,在一个文件中一次交换两个字符,这是有效的,但是如果我尝试多次使用该函数,我所做的以前的交换将从文本文件中删除,原始文本现在返回,因此第二次更改将看起来是我的第一次。我该如何解决这个问题?
void swapping_letters()
{
ifstream inFile("decrypted.txt");
ofstream outFile("swap.txt");
char a;
char b;
vector<char> fileChars;
if (inFile.is_open())
{
cout<<"What is the letter you want to replace?"<<endl;
cin>>a;
cout<<"What is the letter you want to replace it with?"<<endl;
cin>>b;
while (inFile.good())
{
char c;
inFile.get(c);
fileChars.push_back(c);
}
replace(fileChars.begin(),fileChars.end(),a,b);
}
else
{
cout<<"Please run the decrypt."<<endl;
}
for(int i = 0; i < fileChars.size(); i++)
{
outFile<<fileChars[i];
}
}
您可能想要做的是参数化您的函数:
void swapping_letters(string inFileName, string outFileName)
{
ifstream inFile(inFileName);
ofstream outFile(outFileName);
...
因为没有参数,调用它两次相当于:
swapping_letters("decrypted.txt", "swap.txt");
swapping_letters("decrypted.txt", "swap.txt");
但是"decrypted.txt"在第一次调用之后没有被修改,因为你没有改变输入文件。因此,如果你想使用第一个操作的输出作为第二个操作的输入,你必须这样写:
swapping_letters("decrypted.txt", "intermediate.txt");
swapping_letters("intermediate.txt", "swap.txt");
还有其他方法可以解决这个问题。通过一次读取一个字符,您正在进行相当多的函数调用…一个百万字节的文件将涉及100万次get()调用和100万次push_back()调用。大多数情况下,内部缓冲意味着这不会太慢,但有更好的方法:
将整个ASCII文件读入c++ std::string
请注意,如果这是您要解决的实际问题,则实际上不需要将整个文件读入内存。您可以按块读取文件(也可以按字符读取),并在不保存整个文件的情况下执行输出。
在某种程度上,您可能会对内存映射文件感兴趣。这可以让你把磁盘文件当作一个大数组,并且很容易在内存中修改它。同时让操作系统操心一次要换进或换出多少文件的细节。它们很适合解决一些问题,并且boost库中有一个用于内存映射文件的c++平台独立API:
http://en.wikipedia.org/wiki/Memory-mapped_file相关文章:
- 如何在音频处理中使用超能力时间拉伸类
- 出色的文件处理能力
- 控制通过类中的成员函数更改成员变量的能力C++
- 调整STD ::向量的大小是否可以降低其能力
- C 如何确定函数是否有能力被内衬和实际为
- 基于对函数的参数调用流输出运算符的能力重载函数
- 跨不同平台的基本类型的能力
- 将超能力高级音频播放器同步到绝对位置
- 虚幻引擎4:增加自由漫游能力
- 如何以低于相机每秒帧数的能力处理数据?
- RVO和返回矢量,重用能力
- 超能力 NDK 安卓:返回 int 在"extern"块中成功,在调用函数中失败
- 超能力安卓JNI:了解"JNI(jintArray ..."格式
- 如何实现ressize()以更改C 中动态成员数据的能力
- 如何知道我的Nvidia卡在C/C++中的计算能力
- 如何使用 NDK 小于 23 的超能力库构建应用
- 如何让C++课"return"有能力?(或用户定义类型的返回动态)
- 是通过计算能力1.x的设备中的缓存的全局内存负载/商店
- Linux:应用程序响应能力和select()
- 动态数组查找能力