Error writing binary file using fwrite

0

Why this code snippet

DataRootDir data = rootdir[i];
fwrite (data, sizeof(DataRootDir), 1, arq);

always returns error

error: cannot convert 'DataRootDir' to 'const void*' for argument '1' to 'size_t fwrite(const void*, size_t, size_t, FILE*)'|

and how to solve it.

Complete code:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cstring>

using namespace std;

typedef struct DataRootDir {
    int tipo;
    char nome[256];
    char extensao[4];
    int data;
    int hora;
    int tam;
    char atributos;
    int primeiroBloco;
} DataRootDir;

void saveHD(DataRootDir *rootdir){
    FILE *arq;
    arq = fopen("HD.dat", "wb"); // Cria um arquivo binário para gravação

    if (arq == NULL) {
        cout << "Problemas na criação do arquivo" << endl;
    }
    else{

        for(int i = 0; i < 512; i++){
            DataRootDir data = rootdir[i];
            fwrite (data, sizeof(DataRootDir), 1, arq);
        }

        fclose(arq);
    }
}

DataRootDir* createRootDir(){
    DataRootDir *rootdir = (DataRootDir *) malloc(sizeof(DataRootDir) * 512);

    for(int j = 0; j < 512; j++){
        DataRootDir *drd = (DataRootDir *) malloc(sizeof(DataRootDir));
        drd->tipo = 0;
        strcpy(drd->nome, "");
        strcpy(drd->extensao, "");
        drd->data = 0;
        drd->hora = 0;
        drd->tam = 0;
        drd->atributos = '
DataRootDir data = rootdir[i];
fwrite (data, sizeof(DataRootDir), 1, arq);
'; drd->primeiroBloco = 0; rootdir[j] = *drd; } return rootdir; } void insertRootDir(DataRootDir *data, DataRootDir *rootdir){ for(int j = 0; j < 512; j++){ if(strcmp(rootdir[j].nome,"") == 0){ rootdir[j] = *data; break; } } } int main(){ cout << "SIZE OF DataRootDir " << sizeof(DataRootDir) << " Bytes " << endl; cout << "SIZE OF DataRootDir ON ARCHIVE " << sizeof(DataRootDir) * 512 << " Bytes " << (sizeof(DataRootDir) * 512) / 1024 << " KB" << endl; DataRootDir *rootDir = createRootDir(); DataRootDir *drd = (DataRootDir *) malloc(sizeof(DataRootDir)); drd->tipo = 0; strcpy(drd->nome, "Teste"); strcpy(drd->extensao, "txt"); drd->data = 20140219; drd->hora = 850; drd->tam = 35342; drd->atributos = '
error: cannot convert 'DataRootDir' to 'const void*' for argument '1' to 'size_t fwrite(const void*, size_t, size_t, FILE*)'|
'; drd->primeiroBloco = 1; insertRootDir(drd,rootDir); saveHD(rootDir); system("pause"); }
    
asked by anonymous 19.02.2016 / 19:53

1 answer

1

What the error is reporting is that the first argument of the fwrite function expects a pointer you are passing a instance from DataRootDir

Try replacing with

DataRootDir *data = &rootdir[i];
fwrite (data, sizeof(DataRootDir), 1, arq);
    
19.02.2016 / 20:48