无法在c++中向文件中写入消息
Not able to write messages into the file in c++?
如果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;
相关文章:
- C++入门 5 版:类消息和文件夹
- 如何将消息时间戳写入日志文件?
- 避免使用 boost::进程间::消息队列创建文件
- 可以将Boost消息队列文件重定向到用户指定的位置
- 在 BMP 文件中查找隐藏的消息
- 有没有办法在不使用 set_buff() 的情况下从文件中读取并填充消息增益
- 将断言消息写入日志文件
- Visual Studio在发布模式下构建,但用户收到消息说他们需要调试文件
- 如何在消息文件中获取用户定义的字段
- 忽略来自 GDB(终端)中的包含/库文件的调试消息
- 如何从命令行运行可执行文件时启用系统错误消息
- C++ protobuf:如何通过"SerializeToOstream()"将多条消息写入文件
- 是否有 G++ 7.2 选项在使用预编译头文件时发出消息?
- 在.c文件接收函数中使用Linux中的MSGGET创建消息队列未实现错误
- 烦人的错误消息:无法合并以前的GCDA文件
- 包含类文件后的错误消息(多个定义的符号)
- 将PCAP文件解析至C 中的sip消息
- 如何加密用用户输入的文件写的消息
- 如何将多个协议缓冲区的消息写入可附加的压缩文件中?
- 从DLL文件调用消息框函数时出现奇怪的字符