如何将字符串写入二进制文件

发布于 2024-07-15 06:13:20 字数 685 浏览 8 评论 0原文

使用这段代码,我尝试打印字符串“foo”10次 以二进制格式。 但为什么执行此操作的函数不起作用呢?

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

template <typename T> void WriteStr2BinFh (string St, ostream &fn) {
     for (unsigned i = 0; i < St.size(); i++) {
         char CStr = St[i];
         fn.write(&CStr.front(), CStr.size());
     }
     return;
}

int main() {
   string MyStr = "Foo";
   ofstream myfile;
   myfile.open("OuputFile.txt", ios::binary|ios::out);

   // We want to print it 10 times horizontally
   // separated with tab

  for (int i = 0; i < 9; i++) {
      WriteStr2BinFh(Mystr+"\t", myfile);
   }

   myfile.close();   
}

With this code I tried to print the string "foo" 10 times
in binary format. But why doesn't the function to do it work?

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

template <typename T> void WriteStr2BinFh (string St, ostream &fn) {
     for (unsigned i = 0; i < St.size(); i++) {
         char CStr = St[i];
         fn.write(&CStr.front(), CStr.size());
     }
     return;
}

int main() {
   string MyStr = "Foo";
   ofstream myfile;
   myfile.open("OuputFile.txt", ios::binary|ios::out);

   // We want to print it 10 times horizontally
   // separated with tab

  for (int i = 0; i < 9; i++) {
      WriteStr2BinFh(Mystr+"\t", myfile);
   }

   myfile.close();   
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

动听の歌 2024-07-22 06:13:20

这里有很多错误,我只想列出我看到的所有内容:

您的 for 循环条件应该是 i < 10.

为什么使用模板而不使用模板化参数T?

您在 CStr 上调用方法 front() ,但 CStr 是一个字符,而不是字符串,所以我什至不知道它是如何编译的。

假设 CStr 是一个字符串,您不想使用 & 获取 front() 迭代器的地址,而是想这样说:

fn.write(St.c_str(), St.size());

并且您不想循环 St.size() 迭代。 只需执行上述操作即可。

There is so much wrong here, I'm just going to list everything I see:

Your for loop condition should be i < 10.

Why are you using a template but not the templatized parameter T?

You're calling the method front() on CStr, but CStr is a char, not a string, so I don't even know how that compiles.

Assuming CStr was a string, you don't want to take the address of the front() iterator using &, instead you want to say something like:

fn.write(St.c_str(), St.size());

And you don't want to loop for St.size() iterations. Just do the above.

水溶 2024-07-22 06:13:20

天哪,它有很多错误:

  • int main - 应该返回值;
  • 你不使用模板< 类型名称 T > 在你的职能中;
  • Mystr - 函数调用中的名称不正确,C++ 中的名称区分大小写;
  • char CStr - 没有方法 front,也没有 std::string ;
  • 您无法获取第一个元素的地址,例如向量的情况;
  • 如果您接受 std::string 作为 const 引用,那就更好了;
  • 您忘记包含字符串标头;
  • ...

使用代码组织和命名修复了您的示例:

#include <iostream>
#include <fstream>
#include <string>

void WriteStr2BinFh( const std::string& St, std::ostream &out ) 
{
    out.write( St.c_str(), St.size() );
}

int main() 
{
    std::string MyStr = "Foo";
    std::ofstream myfile( "OuputFile.txt", std::ios::binary | std::ios::out );


    for (size_t i = 0; i < 9; ++i) 
    {
        WriteStr2BinFh( MyStr+"\t", myfile );
    }

   myfile.close();   
   return 0;
}

但我建议使用 std::fill_n 算法

std::fill_n( std::ostream_iterator< std::string >( myfile, "\t" ), 10, MyStr );

omg, it have a lot of errors:

  • int main - should return value;
  • you don't use template< typename T > in your function;
  • Mystr - not correct name in function call, names in c++ are case sencetive;
  • char CStr - doesn't have method front, and std::string too;
  • you couldn't get address of first element such as in case with vector;
  • it will be better if you will accept std::string as const reference;
  • you forgot to include string header;
  • ...

fixed your example, with your code organize and your naming:

#include <iostream>
#include <fstream>
#include <string>

void WriteStr2BinFh( const std::string& St, std::ostream &out ) 
{
    out.write( St.c_str(), St.size() );
}

int main() 
{
    std::string MyStr = "Foo";
    std::ofstream myfile( "OuputFile.txt", std::ios::binary | std::ios::out );


    for (size_t i = 0; i < 9; ++i) 
    {
        WriteStr2BinFh( MyStr+"\t", myfile );
    }

   myfile.close();   
   return 0;
}

but I've reccomended to use std::fill_n algorithm

std::fill_n( std::ostream_iterator< std::string >( myfile, "\t" ), 10, MyStr );
花间憩 2024-07-22 06:13:20

首先,char CStr 表示 CStr 是单个字符。 其次, fn.write(&CStr.front(), CStr.size()); 将该字符视为容器,如 std::vector ,这当然无法编译。

假设 WriteStr2BinFh 之前的一切都正常,我还没有检查过,这就是 WriteStr2BinFh 应该(可能)看起来的样子:

void WriteStr2BinFh(const string& St, ostream &fn)
{
    for(string::iterator it = St.begin(); it != St.end(); ++it)
    {
        fn.put(*it);
    }
}

或者,最好是

void WriteStr2BinFh(const string& St, ostream &fn)
{
    fn.write(St.c_str(), St.length());
}

First, char CStr says that CStr is a single character. Second, fn.write(&CStr.front(), CStr.size()); treats that character as a container, like std::vector<>, which of course cannot compile.

Assuming that everything up to WriteStr2BinFh is ok, which I haven't checked, this is how WriteStr2BinFh should (could) look:

void WriteStr2BinFh(const string& St, ostream &fn)
{
    for(string::iterator it = St.begin(); it != St.end(); ++it)
    {
        fn.put(*it);
    }
}

or, preferably

void WriteStr2BinFh(const string& St, ostream &fn)
{
    fn.write(St.c_str(), St.length());
}
摘星┃星的人 2024-07-22 06:13:20

在二进制模式下执行 io 操作的要点:

  • 必须使用标志 ios::out (输出模式)和 ios::binary(二进制模式) 以输出和二进制模式打开文件
  • 函数 write 有两个参数。 第一个参数是 char* 类型,表示要写入的数据,第二个参数是 int 类型,询问要写入二进制文件的数据大小。
  • 文件必须在最后关闭。

    void write_to_binary_file(网站 p_Data) 
      { 
          fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app); 
          binary_file.write(reinterpret_cast(&p_Data),sizeof(WebSites)); 
          二进制文件.close(); 
      } 
      

    此 I/O 二进制函数将一些数据写入该函数。

  • 文件使用 ios::out 和 ios::binary 以输出和二进制模式打开。
    还有一个说明符 ios::app,它告诉操作系统该文件也是以附加模式打开的。 这意味着任何新的数据集都将附加到文件末尾。

  • 上面使用的write函数,需要参数为字符指针类型。 因此我们使用类型转换器reinterpret_cast将结构体类型转换为char*类型。

Important points for doing an io operation in binary mode:

  • The file has to be opened in output and binary mode using the flags ios::out (output mode) and ios::binary( binary mode)
  • The function write takes two parameters. The first parameter is of type char* for the data to be written and the second is of type int asking for the size of data to be written to the binary file.
  • File has to be closed at the end.

    void write_to_binary_file(WebSites p_Data)
    {
        fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
        binary_file.write(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
        binary_file.close();
    }
    

    This I/O binary function writes some data to the function.

  • The file is opened in output and binary mode with ios::out and ios::binary.
    There's one more specifier ios::app, which tells the Operating system that the file is also opened in append mode. This means any new set of data will be appended to the end of file.

  • The write function used above, needs the parameter as a character pointer type. So we use a type converter reinterpret_cast to typecast the structure into char* type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文