写入文件时指针发出问题。分段故障

时间:2017-09-25 12:01:40

标签: c++11 pointers struct binary segmentation-fault

我正在尝试将字节序列写入二进制文件。 将结构转换为二进制并存储在指针中,并以相同的大小递增指针,然后我将该指针的地址保存到另一个指针,以便最后我可以将整个数据从头到尾写入文件。 这是一个代码:

#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct OhlData_struct
{
        int volume;

}__attribute__((__packed__));

struct StrCar
{
     int PhoneNo;
     long Model;
}__attribute__((__packed__));
int main()
{
    StrCar Car;
    OhlData_struct header;
    char *Data=(char *)calloc(0,(sizeof(OhlData_struct) + (sizeof(StrCar) * 10)));
    char *temp;
    temp = Data;
    string filename = "mydatastream_binary.txt";
    ofstream outfile;
    outfile.open (filename.c_str(), ios::out | ios::binary);

    header.volume=123;
    memcpy(Data,(char*) &header, sizeof(struct OhlData_struct));
    Data += sizeof(struct OhlData_struct);
    int i=0;
    while(i <10)
    {
            Car.PhoneNo=101+i;
            Car.Model=1001+i;
            memcpy(Data,(char*) &Car, sizeof(struct StrCar));

            outfile_copy.write (Data, sizeof(StrCar));
            Data += sizeof(struct StrCar);
            i++;
    }

     outfile.write (temp, (sizeof(struct OhlData_struct) + (sizeof(struct StrCar) * 10)));
    cout << "\n\nFile writeing done\n\n";

outfile.write给出&#34;分段错误&#34 ;;

任何人都可以告诉如何将整个DATA写入文件吗?我在哪里需要更改代码!!

尝试了很多,但仍然无法将确切的二进制数据存入文件, 我是C ++的新手,这个指针不在我的脑海里。

0 个答案:

没有答案
相关问题