How to pass structure data to a text file?

0

I have this structure:

struct televisao {
    int id_guit;
    int precodia;
    int preco;
    int estado;
    char nome[20];
};

I wanted to ask the user to insert data from this structure and save it to a .txt file, how do I get it? The part of verifying that the file exists can do with itself.

    
asked by anonymous 30.05.2018 / 20:18

2 answers

2

A simple way to have control as the data is written to the file is to use fprintf . This is identical to printf with the difference that the first parameter is where the information will be written.

Example:

FILE *ficheiro = fopen ("teste.txt","w");
struct televisao tv;
//preencher tv com os dados que interessam
fprintf (ficheiro,"%d,%d,%d,%d,%s\n",tv.id_guit, tv.precodia, tv.preco, tv.estado,tv.nome);
fclose (ficheiro);

In this example, I used , as a separator, which looks like I would create a csv file, however, the format in which the data is written to the file is entirely at your discretion.

    
30.05.2018 / 20:41
0

You can use the fwrite function.

#include <stdio.h>

int main (){
  struct televisao tv;
  FILE *pFile;
  pFile = fopen ("arquivo.bin", "wb");
  fwrite (tv , sizeof(tv), 1, pFile);
  fclose (pFile);
  return 0;
}

Read more at cplusplus .

    
30.05.2018 / 20:37