服务器状态到 XML 使用 fwrite?
Server Status to XML using fwrite?
// Update the server status xml
string filelocation ("/var/www/html/index.xml");
string firstline ("<server>n");
string secondline ("t<current>" + msg.getCount() + "</current>n");
string thirdline ("t<highest>" + "--" + "</highest>n");
string fourthline ("t<status>Online</status>n")
string finalline ("</server>");
fstream file;
file.open(filelocation);
file.write(firstline + secondline + thirdline + fourthline + finalline);
string updateFlush ("Server Status updated.");
printf("%sn", updateFlush);
file.close();
请注意,msg.getCount(( 是同一文件中的函数,用于从中央服务器获取玩家计数。
给出有关操作数常量字符*的错误。与 + 或 - 有关
谢谢
看看这条线
string secondline ("t<current>" + msg.getCount() + "</current>n");
"t<current>"
是一个const char *
msg.getCount()
看起来像int
或size_t
</current>n
又是const char *
将const char *
添加到int
或size_t
会创建一个指向其他地址的新const char *
。
同样的情况也发生在行中
string thirdline ("t<highest>" + "--" + "</highest>n");
在这里,您将指针添加到一起。结果是一个指向或多或少随机地址的指针。
在这两行中:
string updateFlush ("Server Status updated.");
printf("%sn", updateFlush);
您正在创建一个C++字符串对象,并尝试使用 C 打印函数打印它,该函数的格式字符串需要char *
。
您正在将基于 C 和 C++ 或基于流的 I/O 与传统 I/O 混合使用。
在当前C++您应该这样做:
string filelocation ("/var/www/html/index.xml");
fstream file;
file.open(filelocation);
file
<< "<server>n"
<< "t<current>" << msg.getCount() << "</current>n"
<< "t<highest>" << "--" << "</highest>n"
<< "t<status>Online</status>n"
<< "</server>";
string updateFlush ("Server Status updated.");
cout << updateFlush << std::endl;
file.close();
甚至更具可读性:
auto file = std::ofstream("/var/www/html/index.xml");
file
<< "<server>" << std::endl
<< "t<current>" << msg.getCount() << "</current>" << std::endl
<< "t<highest>" << "--" << "</highest>" << std::endl
<< "t<status>Online</status>" << std::endl
<< "</server>";
file.close();
std::cout << "Server status updated." << std::endl;
如果使用流进行操作,请使用 std::endl 输出换行符。它为操作系统(CRLF 或 LF 或其他(输出正确的换行符,并刷新流。
要使用 std::cout,您必须包含<iostream>
,对于 std::ofstream 包括<fstream>
。
如果你喜欢它简短,你甚至可以这样做:
std::ofstream("/var/www/html/index.xml")
<< "<server>" << std::endl
<< "t<current>" << msg.getCount() << "</current>" << std::endl
<< "t<highest>" << "--" << "</highest>" << std::endl
<< "t<status>Online</status>" << std::endl
<< "</server>";
std::cout << "Server status updated." << std::endl;
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 服务器状态到 XML 使用 fwrite?
- 使用 fwrite() 和 fread() 进行二进制输入/输出
- 使用 fwrite/fread 对矩阵进行二进制(反)序列化不起作用
- 尝试使用带有模式"a+"的 fwrite() 将新文本附加到现有文件中,但写入奇怪的字符串
- 如何使用fseek和fwrite将文本插入到文件中
- 为什么要使用fopen打开流,并使用读/写(而不是fread/fwrite)执行I/O
- 如果要显式指定缓冲区大小,应使用 Fread/FWRITE 还是读/写系统调用
- 我正在尝试使用 fread 和 fwrite 来制作复制函数,但根据缓冲区大小,我不断得到奇怪的输出
- 使用fread/fwrite将文件复制到USB的性能
- 使用fwrite C++将压缩数据写入文件
- 在大文件上使用fwrite导致字节损坏
- 使用fgetc/fwrite更改简单字节失败
- 如何像直接访问文件一样使用内存:类似于read和fwrite函数
- Libcurl: image在使用fstream::write而不是fwrite时被损坏