write struct to file

Asked

Viewed 1,331 times

0

I’m trying to record a struct in a file via language c. But whenever I run the program on xcode nothing is recorded in the archive.

I have tried the file permissions system, but there is nothing wrong.

code:

//
//  main.c
//  arquivos3
//
#include <stdio.h>
#include <stdlib.h>

struct Pessoa{
    char nome[20];
    unsigned int idade;
    float altura;
};

int main(int argc, const char * argv[]) {
    // insert code here...
    FILE* ptr;
    char* filename = "arq_teste.dat";
    char* modo_gravacao = "w";
    struct Pessoa pessoa = {"Fernando Santos", 42, 1.75};

    //Abre o arquivo para gravação; se ocorrer erro o programa aborta.
    if ((ptr = fopen(filename, modo_gravacao)) == NULL) {
        puts("Erro ao abrir o arquivo!");
        exit(1);
    }

    fwrite(&pessoa, sizeof(struct Pessoa), 1, ptr);

    fclose(ptr);



    return 0;
}
  • Your write mode should be "Wb" as you are not working with a text file.

  • It’s not in this code, but I’ve tried it this way.

  • Here it worked properly and generated a binary file.

2 answers

1

1) You are not sure in what context your program is running from xcode and hence, your output file is being written somewhere "unknown" on your file system.

Ensure that the output file will be recorded in the same directory in which the executable is located:

char* filename = "./arq_teste.dat";

2) You are writing the contents of a structure directly into a file and need to do so in binary mode:

char* modo_gravacao = "wb";

3) To better understand the problem, you need a more complete error handling, for example:

#include <stdio.h>
#include <stdlib.h>

struct Pessoa {
    char nome[20];
    unsigned int idade;
    float altura;
};

int main(void)
{
    FILE* ptr;
    char* filename = "./arq_teste.dat";
    char* modo_gravacao = "wb";
    struct Pessoa pessoa = {"Fernando Santos", 42, 1.75};

    if ((ptr = fopen(filename, modo_gravacao)) == NULL) {
        puts("Erro ao abrir o arquivo!");
        return 1;
    }

    if(fwrite(&pessoa, sizeof(struct Pessoa), 1, ptr) != 1) {
        puts("Erro ao gravar conteudo no arquivo!");
        fclose(ptr);
        return 1;
    }

    fclose(ptr);

    puts("Arquivo gravado com sucesso!");
    return 0;
}

0

The fwrite() should be replaced by

fprintf(ptr, "%s %d %f", pessoa.nome, pessoa.idade, pessoa.altura);

Just use the Wordpad and you can see how it’s going.

With fprintf you can choose how you want to record, which is an advantage, for example

fprintf(ptr, "%s-%d-%f", pessoa.nome, pessoa.idade, pessoa.altura); ^

  • 1

    Note that the questioner wishes to save a binary file and not a text file. It makes no sense, in this case, to replace fwrite with fprintf.

Browser other questions tagged

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