Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Structs to a file in c [closed]

Is it possible to write an entire struct to a file

example:

struct date {     char day[80];     int month;     int year; }; 
like image 872
amarVashishth Avatar asked Jun 08 '13 07:06

amarVashishth


People also ask

Can I write a struct to a file C?

Open file to write. Check if any error occurs in file opening. Initialize the variables with data. If file open successfully, write struct using write method.

How do you use struct in another file?

The easy solution is to put the definition in an header file, and then include it in all the source file that use the structure. To access the same instance of the struct across the source files, you can still use the extern method.

Which functions can be used to read and write a structure into files?

For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.


1 Answers

Is it possible to write an entire struct to a file

Your question is actually writing struct instances into file.

  1. You can use fwrite function to achieve this.
  2. You need to pass the reference in first argument.
  3. sizeof each object in the second argument
  4. Number of such objects to write in 3rd argument.
  5. File pointer in 4th argument.
  6. Don't forget to open the file in binary mode.
  7. You can read objects from file using fread.
  8. Careful with endianness when you are writing/reading in little endian systems and reading/writing in big endian systems and viceversa. Read how-to-write-endian-agnostic-c-c-code

    struct date *object=malloc(sizeof(struct date)); strcpy(object->day,"Good day"); object->month=6; object->year=2013; FILE * file= fopen("output", "wb"); if (file != NULL) {     fwrite(object, sizeof(struct date), 1, file);     fclose(file); } 

You can read them in the same way....using fread

    struct date *object2=malloc(sizeof(struct date));     FILE * file= fopen("output", "rb");     if (file != NULL) {         fread(object2, sizeof(struct date), 1, file);         fclose(file);     }     printf("%s/%d/%d\n",object2->day,object2->month,object2->year); 
like image 151
pinkpanther Avatar answered Sep 23 '22 00:09

pinkpanther