Error writing binary file using fwrite

Asked

Viewed 155 times

0

Why this code snippet

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

always returns the 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 resolve.

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 = '\0';
        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 = '\0';
    drd->primeiroBloco = 1;

    insertRootDir(drd,rootDir);

    saveHD(rootDir);

    system("pause");
}

1 answer

1


What the error is stating is that the first argument of the function fwrite expecting a pointer you’re passing a instance of DataRootDir

Try to replace with

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.