在文件上重用时,Fstream 会出错

Fstream gives error when reused on a file

本文关键字:Fstream 出错 文件      更新时间:2023-10-16

我有两个文本文件。原始输出:

Log.txt
Joe hello
Joe gargabash
Joe random unnecessary text
Hello
How are you?

Log2.txt 是另一个最初为空白的文本文件。

当我运行此代码时,它成功地复制了所有不以 Joe 开头的行。但是,我想将文本复制回原始.txt。当我取消注释掉我评论的选择以尝试这样做时,我收到错误。有人知道我做错了什么吗?非常感谢您阅读所有这些混乱。为了澄清起见,bool STRINGCONTAINS(int, char, char, int) 检查一个 char 数组是否与另一个 char 数组匹配。

#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>

using namespace std;
bool STRINGCONTAINS(bool CaseSensitive, //If this is true, we are checking a case sensitive string, if it's false, we're not.
                  char * input1, // First string [Type: Char Array]
                  char * input2, //Second String [Type: Char Array]
                  int MAXSTRINGLENGTH) // Integer representing max possible length of string.
{
    if (CaseSensitive) 
    {
        for(int i=0;i<MAXSTRINGLENGTH;i++) 
        {
            if (*input1 == *input2) 
            {
                input1++; 
                input2++; 
            } else
            {
                return 0;
            }
        } 
    } else 
    {
        int char1, char2; 
        for(int i=0;i<MAXSTRINGLENGTH;i++) 
        {
            char1 = *input1; 
            char2 = *input2; 
            if (char1 == char2 || char1 == (char2+32) || char2 == (char1+32)) 
            {
                input1++; 
                input2++; 
            } else 
            {
                return 0;
            }
        } 
    }
    return 1;
}

int main() {
    int input;
                    char * loadedline = new char[192];
                    ifstream log;
                    ofstream templog;
                    log.open("log.txt");
                    templog.open("log2.txt");
                    while(log.getline(loadedline,sizeof(log)))
                    {
                        if (!STRINGCONTAINS(0,loadedline,"joe",3))
                        {
                        cout << loadedline << endl;
                        templog << loadedline << endl;
                        }
                    }
                    log.close();
                    templog.close();
                    /*ifstream templog2;
                    ofstream log2;
                    templog2.open("log2.txt");
                    log2.open("log.txt");
                    while(templog2.getline(loadedline,sizeof(templog2)))
                    {
                        log2 << loadedline << endl;
                    }
                    templog2.close();
                    log2.close;*/
                    delete[] loadedline;
                    cin >> input;
                    return 0;
}

程序中的错误是log2.close.中缺少括号

将其更改为log2.close();,它将运行!