How to pass structure data to a text file?

Asked

Viewed 104 times

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 store it in a . txt file, how can I? The part of checking if the file exists I can do.

2 answers

2

One easy way to control how data is written to the file is to use fprintf. This is identical to the printf except that the first parameter is where the information will be written to.

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 acts as if creating a file csv, however, the format in which the data is written to the file is entirely at your discretion.

0

You can use the function fwrite.

#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 on cplusplus.

Browser other questions tagged

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