Just as I promised, we will write and subsequently read back a C structure! One caveat though: you need to know about binary files. You can learn more in the previous article.
For testing, the following structure will be used:
struct TestStruct
{
int a;
double b;
};
First, a connection to a file, specifically, a binary file is needed. Next, we create an instance of TestStruct
and set our desired values. Finally, using fwrite()
to write the structure into the file.
#include <stdio.h>
typedef struct
{
int a;
double b;
} TestStruct;
int main(void)
{
FILE *file = fopen("test", "wb");
TestStruct ts;
ts.a = 105;
ts.b = 194.543;
fwrite(&ts, sizeof(TestStruct), 1, file);
fclose(file);
}
Output:
~/Desktop
➜ clang main.c
~/Desktop
➜ ./a.out
~/Desktop
➜ cat test
i!VL7�A`Qh@%
~/Desktop
➜
Trying to output a file that is saved with a C structure results in garbage.
Let's now read back in the data and see if everything is still correct.
#include <stdio.h>
typedef struct
{
int a;
double b;
} TestStruct;
int main(void)
{
FILE *file = fopen("test", "rb");
TestStruct ts;
fread(&ts, sizeof(TestStruct), 1, file);
fclose(file);
printf("ts.a = %d\nts.b = %f\n", ts.a, ts.b);
}
Output:
~/Desktop
➜ clang main.c
~/Desktop
➜ ./a.out
ts.a = 105
ts.b = 194.543000
~/Desktop
➜
Everything was written and read properly.
Next
This is a short article and there is more to explore but I feel everything that was taught in this series will provide many people with adequate knowledge to accomplish basic and more difficult problems relating to files.
Top comments (0)