1

Can I save a structure in a file, for example to a txt?. And also if I can, would it be possible to reopen it and get the data back?

Maybe something like this:

struct guest
{
        int tel;
        char name[20];
        char country[20];
} ;

int main()
{

        record.tel=231231;
        strcpy(record.name, "Raju");
        record.country= China;
Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82

4 Answers4

1
fprintf(file, "%d %20s %20s\n", record.tel, record.name, record.country);
fscanf(file, "%d %20s %20s\n", &record.tel, &record.name, &record.country);

UPD: if name and/or country may contain spaces, use the following to read back:

char blank[1];

fscanf(file, "%d ", &record.tel);
fread(record.name, 20, 1, file);
fread(blank, 1, 1, file); // assert(blank[0] == ' ');
fread(record.country, 20, 1, file);
fread(blank, 1, 1, file); // assert(blank[0] == '\n');
user3125367
  • 2,920
  • 1
  • 17
  • 17
1

Functionality you describe is called serialization.
There are a lot of information in the internet. for ex. refer to the:
Data serialization in C?

Community
  • 1
  • 1
spin_eight
  • 3,925
  • 10
  • 39
  • 61
1

Basically you can. You have two choises.

1) As a binary that is not portable.

//  Writing to a file inticaded by fp ...
fwrite( &record, sizeof(struct guest), 1, fp );

// Reading from a file inticaded by fp ... 
fread( &record, sizeof(struct guest), 1, fp ); 

2) As a text, which is portable.

//  Writing to a file inticaded by fp ...
fprintf( fp, "%d %20s %20s", record.tel, record.name, record.country );

// Reading from a file inticaded by fp ... 
fscanf( fp, "%d %s %s", &record.tel, &record.name, &record.country );

With first choice (binary) you can read directly from the file, see an example here, if you save it as a text you will have to read line by line and give values ​​manually in the fields of the struct.

Perefexexos
  • 252
  • 1
  • 8
1

If its your first time use fprintf() / fscanf() and no printf() / scanf()