服务器状态到 XML 使用 fwrite?

Server Status to XML using fwrite?

本文关键字:fwrite 使用 XML 状态 服务器      更新时间:2023-10-16
// 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()看起来像intsize_t</current>n又是const char *

const char *添加到intsize_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;