无法正确使用fwrite

时间:2018-06-04 11:42:30

标签: c cs50

我无法弄清楚如何在这里使用fwrite。我遇到了分段错误。有没有其他方法可以写入0x00到rgbtRed,rgbtBlue和rgbtGreen?我在网上查了一下,但找不到合适的方法。

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

typedef uint8_t  BYTE;

typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

int main (void)
{

    RGBTRIPLE triple;
    /*code which opens a bmp file, copies it and exports it to another 
    file based on the changes which I ask it.
    I'm trying to set R's (of RGB) value to 0 to see if that solves  
    the problem. I'm trying to figure out how to set the value to 0*/

    fwrite(&triple.rgbtRed, sizeof(uint8_t), 1, 0x00);


}

2 个答案:

答案 0 :(得分:2)

fwrite用于写入文件,但是你想将内存设置为零,这不是一回事。

使用这行代码,整个triple结构设置为零。

memset(&triple, 0, sizeof triple);

答案 1 :(得分:0)

应该打开fwrite的第四个参数来编写FILE

归零会导致异常

FILE * aFileYouWrite = fopen("afilename.xyz","wb");
memset(&triple, 0, sizeof triple); 
fwrite(&triple.rgbtRed, sizeof(uint8_t), 1, aFileYouWrite );