无法在c++中向文件中写入消息

Not able to write messages into the file in c++?

本文关键字:消息 文件 c++      更新时间:2023-10-16

如果processName不在sysSettings文件中,您认为有什么原因不会将其写入sysSettings文件吗??我不知道为什么它没有写在那里。请帮忙!!!

void pushSysSet(const char* processName)
    {
        char oneLine[15];
        fstream sysSettings;
        sysSettings.open("p_appmanager/src/sys_settings.txt",ios::in | ios:: out | ios::app);
        if(!sysSettings.is_open())
        {
            if(debugFlag)
            {
                cout<<currentTime()<<"::"<<"Unable to open sys_settings file"<<strerror(errno)<<endl;
                cout.flush();
            }
            return;
        }
        while(!((sysSettings.getline(oneLine,sizeof(oneLine))).eof()))
        {
            if(!strcmp(oneLine,processName))
                return;
        }
        sysSettings<<processName;
        sysSettings.flush();
        sysSettings.close();
    }

永远不要使用eof()来控制循环。所有的C字符串是怎么回事?

void pushSysSet(const char* processName)
{
    fstream sysSettings("p_appmanager/src/sys_settings.txt", ios::in | ios::out | ios::app);
    if(!sysSettings)
    {
        if(debugFlag)
        {
            cout<<currentTime()<<"::"<<"Unable to open sys_settings file"<<strerror(errno)<<endl;
            cout.flush();
        }
        return;
    }
    std::string oneLine;
    while(std::getline(sysSettings, oneLine))
    {
        if(oneLine == processName)
            return;
    }
    sysSettings.clear();
    sysSettings << processName << 'n';
}

我稍微清理了一下代码。如果你没有检查结果,那么在超出范围之前进行单独的刷新和关闭是没有意义的;那是析构函数的一部分。使用std::string来消除可能的缓冲区溢出或截断的名称,通常是为了让事情变得更好。已清理while循环的条件。

我还在processName输出后添加了一行换行符:由于您的阅读代码显然希望该内容单独出现在一行中,因此只有在编写代码时才能确保这一点。

最后,正如Casey所指出的,一旦你读取了整个文件,流就处于错误状态,不会对你的写入做出响应,所以先清除状态。

由于设置了eof位,将processName写入流失败。在写入之前,用sysSettings.clear()清除流的错误状态标志

while(!((sysSettings.getline(oneLine,sizeof(oneLine))).eof()))
{
        if(!strcmp(oneLine,processName))
            return;
}
sysSettings.clear();
sysSettings<<processName;