简体   繁体   English

C ++在一项任务中读/写txt文件->交换字符

[英]C++ read/write txt file in one task -> exchanging chars

I try to open a txt File for reading / writing in one task. 我尝试打开一个txt文件以在一项任务中进行读取/写入。 My prior target is to exchange some characters by the saved ones in an array: 我之前的目标是通过数组中保存的字符交换一些字符:

   void Inputfile::decryptFile(string filename)
{
    for(int i=0;i<15;i++)
    {
        fstream filedest(filename.c_str(), ios::in | ios::out);
        if(!filedest)
            cerr << "Konnte Zieldatei nicht oeffnen!\n";
        else 
            cout << endl << filename << " geoeffnet zum entschluesseln!\n";

        while(!filedest.eof())
        {
            filedest.get(ch);
            if(ch == char(this->mostcharsencrypted[i]))
            {
                filedest.put(char(this->mostchars[i]));
            }

        }
        filedest.close();
        cout << "Fertig!";
    }
}

mostcharsencrypted[] and mostchars[] are integer Arrays that hold the characters. mostcharsencrypted []和mostchars []是保存字符的整数数组。 I am sure that there is just 8 Bit Ansii Value in, and I check that even before this method gets called. 我确信其中只有8位Ansii值,并且即使在调用此方法之前,我也要进行检查。

So if the currently read character is the one at the current array position (i: 0 - 14) then i want to exchange the character in the txt-file with the one from mostchars[]. 因此,如果当前读取的字符是当前数组位置(i:0-14)上的那个,那么我想与大多数字符[]中的那个交换txt文件中的字符。

Currently I can see that I get exactly the type of matches, but my txt file still shows the same content. 目前,我可以看到完全符合的类型,但是我的txt文件仍显示相同的内容。

When replacing a file, usually two separate streams are used for input and output individually. 替换文件时,通常两个单独的流分别用于输入和输出。 If you need to use one stream for both input and output, the while loop will be like the following: 如果需要将一个流同时用于输入和输出,则while循环将如下所示:

while(filedest)
{
    streampos p = filedest.tellg();
    if(!filedest.get(ch)) break;
    filedest.seekp(p);
    char ch2 = (ch == char(this->mostcharsencrypted[i])) ?
        char(this->mostchars[i]) : ch;
    filedest.put(ch2);
    filedest.sync();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM