将文件字节写入文件客户端 C++

writing file bytes to a file client side c++

我有一个服务器 (python),它使用 C++ 将字节从文件发送到客户端。我正在使用 libcurl 向 python 服务器发出请求,并使用 flask 为我在 python 中完成所有“艰巨”的工作。从服务器获取文件字节后,我想将其写入客户端的 zip 文件。最初,我打算使用 libcurl 为我做这件事,但我决定我不想那样做,因为它需要在我的包装器中添加一个不必要的额外功能。

FILE* zip_file = fopen(zip_name, "wb");
//make request and store the bytes from the server in a string
fwrite(response_information.first.c_str(), sizeof(char), sizeof(response_information.first.c_str()), zip_file);
//response_information is a pair . First = std::string, Second = curl response code

我确实计划切换到 fopen_s(fopen 的安全版本),但我想先获得一个工作程序。这是一个更大项目的一部分,所以我无法提供 运行 的代码。我认为可能导致此问题的一些注意事项:将响应存储为字符串,然后尝试获取 C 字符串版本并将其写入文件。当存储 fwrite 的 return value/code 时,我得到“8”,这显然意味着写入了“*”字节。此外,当我在 windows 上时,它说文件在我 运行 我的程序之后被修改,但 zip 文件本身没有任何内容。如何将响应字节写入文件?

fwrite中的第三个参数是要写入的项目数。所以 sizeof 似乎不是你需要的东西。 response_information.first.c_str()是一个指针,所以sizeof(response_information.first.c_str())returns是一个指针大小。这里应该是:

fwrite(response_information.first.c_str(), sizeof(char), strlen(response_information.first.c_str()), zip_file);

fwrite(response_information.first.c_str(), sizeof(char), response_information.first.length(), zip_file);