How to write a string with padding to binary file using fwrite?

情到浓时终转凉″ 提交于 2020-02-08 10:02:12

问题


My requirement is to write a "32-byte string indicating the units of pressure" to a binary file. The units of pressure I am wanting to write is "Pa" as a 32-byte string. And here is my attempt.

#include <stdio.h>
#include <string>

using namespace std;

int main()
{
  FILE *myFile;
  myFile = fopen ("input_file.dat", "wb");
  //Units
  string units = "Pa";
  //Write Units
  fwrite (&units, 1, 32, myFile);
  fclose (myFile);
  return 0;
}

I'm expecting (conversion of Pa to binary in 32 bytes). The "00100000" are spaces. How do I append those to just Pa?

01010000 01100001 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000 00100000

However, I'm seeing


回答1:


The string "Pa" is only 2 bytes (3 if you count the null terminator), but you want to write out 32 bytes to your file. So you need to pad the string with 30 space characters. There are many different ways you can handle this:

char units[32] = "Pa";
memset(units+2, ' ', 30);
fwrite (units, 1, 32, myFile);
std::string units = "Pa";
std::string padding(32-units.size(), ' ');
fwrite (units.c_str(), 1, units.size(), myFile);
fwrite (padding.c_str(), 1, padding.size(), myFile);
std::string units = "Pa";
std::ostringstream oss;
oss << std::setw(32) << std::setfill(' ') << std::left << units;
std::string s = oss.str();
fwrite (s.c_str(), 1, s.size(), myFile);

That being said, since you are using C++, you should be using C++ style file I/O instead of C style file I/O, eg:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

int main() {
    ofstream myFile ("input_file.dat", ios::binary);
    string units = "Pa";
    myFile << setw(32) << setfill(' ') << left << units;
    return 0;
}



回答2:


You can't write a string directly to a file, you are writing the contents of the string class to your file, this is probably something like a pointer and a size, not the character data.

The simple fix is to make the following change to write the character data (this includes a null terminator, if you don't want that remove the +1):

fwrite (units.c_str(), 1, units.size() + 1, myFile);

The other alternative is to use c++ streams which can write a string directly:

#include <fstream>
#include <string>

int main()
{
  std::ofstream myFile("input_file.dat", std::ios_base::binary);
  //Units
  string units = "Pa";
  //Write Units
  myFile << units;
  return 0;
}


来源:https://stackoverflow.com/questions/58258898/how-to-write-a-string-with-padding-to-binary-file-using-fwrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!