保持文本文件从擦除在一个函数,但保持能力写到它?c++

Keep a text file from wiping in a function but keep ability to write to it? C++

本文关键字:能力 c++ 函数 文件 文本 擦除 一个      更新时间:2023-10-16

我有一个函数,在一个文件中一次交换两个字符,这是有效的,但是如果我尝试多次使用该函数,我所做的以前的交换将从文本文件中删除,原始文本现在返回,因此第二次更改将看起来是我的第一次。我该如何解决这个问题?

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