473,466 Members | 1,447 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

trouble, writing an array of structure to binary file.

Hi!

In my code, I have an array of a structure, which I want to save to a
binary file. When the array is just created, everything works fine, but
when I change contents of the array, saving results in a file, which
doesn't hold the information of the changed array anymore. I dont know why.

Here is the code:

/*

1. loadDirectory() loads records from a binary file into an Array (of table_elements)
2. The address of the first element of the array is stored in 'records'.
3. saveDirectory() should save the array to a file again.

My problem is now: when I change some array elements and then save the
array to a file, and then reload the file via loadDirectory, the content of the
array-elements has changed. I dont know why.

*/

#define DIRECTORY_FILE "index.directory"

typedef struct {
int local_depth;
int elements;
int address;
} table_element;
table_element *records;
int global_depth;
int loadDirectory() {
FILE *directoryFile = fopen (DIRECTORY_FILE, "rb");

if (directoryFile != NULL) {
fread ( &global_depth, sizeof (int), 1, directoryFile);

printf ("Global Depth = %d\n", global_depth);

int size = (int) pow(2,global_depth);
printf ("Size = %d\n", size);
table_element e[size];
table_element eintrag;
int i;
for (i=0; i < (int) pow(2,global_depth); i++) {
fread ( &eintrag, sizeof (table_element), 1, directoryFile);
printf ("I've read the following: Local-Depth = %d, Elements = %d, Address = %d\n", eintrag.local_depth, eintrag.elements, eintrag.address);
e[i] = eintrag;
}
records = e;
return 0;

} else return -1;
}

void saveDirectory () {
FILE *fdirectory = fopen (DIRECTORY_FILE, "wb");

if (fdirectory != NULL) {

fwrite (&global_depth, sizeof (int), 1, fdirectory);
fwrite (records, sizeof (table_element), (int) pow (2,global_depth), fdirectory);

fclose (fdirectory);
}
}

Thank you in advance. If the output is unreadable, have a look at
http://nopaste.php-q.net/63414

Greets Jens
Nov 14 '05 #1
4 5611
Jens Mittag wrote:

Hi!

In my code, I have an array of a structure, which I want to save to a
binary file. When the array is just created, everything works fine, but
when I change contents of the array, saving results in a file, which
doesn't hold the information of the changed array anymore. I dont know why.

Here is the code:

/*

1. loadDirectory() loads records from a binary file into an Array (of table_elements)
2. The address of the first element of the array is stored in 'records'.
3. saveDirectory() should save the array to a file again.

My problem is now: when I change some array elements and then save the
array to a file, and then reload the file via loadDirectory, the content of the
array-elements has changed. I dont know why.

*/

#define DIRECTORY_FILE "index.directory"

typedef struct {
int local_depth;
int elements;
int address;
} table_element;

table_element *records;
int global_depth;

int loadDirectory() {
FILE *directoryFile = fopen (DIRECTORY_FILE, "rb");

if (directoryFile != NULL) {
fread ( &global_depth, sizeof (int), 1, directoryFile);

printf ("Global Depth = %d\n", global_depth);

int size = (int) pow(2,global_depth);
printf ("Size = %d\n", size); table_element e[size];
table_element eintrag;
int i;
These declaration belong way up there, under FILE *... As it is
it should not even compile under any self-respecting C compiler.
for (i=0; i < (int) pow(2,global_depth); i++) {
fread ( &eintrag, sizeof (table_element), 1, directoryFile);
printf ("I've read the following: Local-Depth = %d, Elements = %d, Address = %d\n", eintrag.local_depth, eintrag.elements, eintrag.address);
e[i] = eintrag;
}
records = e;
e is local. At function exit its contents are lost and its
address becomes meaningless.
return 0;
However the file is still open. Naughty.

} else return -1;
}

void saveDirectory () {
FILE *fdirectory = fopen (DIRECTORY_FILE, "wb");

if (fdirectory != NULL) {

fwrite (&global_depth, sizeof (int), 1, fdirectory);
fwrite (records, sizeof (table_element), (int) pow (2,global_depth), fdirectory);

fclose (fdirectory);
}
}

Thank you in advance. If the output is unreadable, have a look at
http://nopaste.php-q.net/63414


Try to publish complete, compilable, source which demonstrates the
problem. Also limit line length to 65 or so, and do not use //
comments or tabs in newsgroups.

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 14 '05 #2
Am Sun, 06 Jun 2004 16:19:13 +0000 schrieb CBFalconer:
Try to publish complete, compilable, source which demonstrates the
problem. Also limit line length to 65 or so, and do not use //
comments or tabs in newsgroups.


Thanks. Will try all the stuff you mentioned.

Jens
Nov 14 '05 #3


Jens Mittag wrote:
Hi!

In my code, I have an array of a structure, which I want to save to a
binary file. When the array is just created, everything works fine, but
when I change contents of the array, saving results in a file, which
doesn't hold the information of the changed array anymore. I dont know why.

Here is the code:

/*

1. loadDirectory() loads records from a binary file into an Array (of table_elements)
2. The address of the first element of the array is stored in 'records'.
3. saveDirectory() should save the array to a file again.

My problem is now: when I change some array elements and then save the
array to a file, and then reload the file via loadDirectory, the content of the
array-elements has changed. I dont know why.
You have not shown code that details how you came to this
conclusion. Because of this, one cannot specifically point to
the cause of the unexpected behavior. However, in the code you
have provided, there is one glaring error in function
LoadDirectory involving the creation of the array.

*/

#define DIRECTORY_FILE "index.directory"

typedef struct {
int local_depth;
int elements;
int address;
} table_element;
table_element *records;
int global_depth;
int loadDirectory() {
FILE *directoryFile = fopen (DIRECTORY_FILE, "rb");

if (directoryFile != NULL) {
fread ( &global_depth, sizeof (int), 1, directoryFile);

printf ("Global Depth = %d\n", global_depth);

int size = (int) pow(2,global_depth);
printf ("Size = %d\n", size);
table_element e[size];
e is declared and exists only in function loadDirectory.

table_element eintrag;
int i;
for (i=0; i < (int) pow(2,global_depth); i++) {
fread ( &eintrag, sizeof (table_element), 1, directoryFile);
printf ("I've read the following: Local-Depth = %d, Elements = %d, Address = %d\n", eintrag.local_depth, eintrag.elements, eintrag.address);
e[i] = eintrag;
}
records = e;
The global pointer, records, points to this function's local array. Once
the function concludes its execution, the local variable will cease
to exist and the value of records is useless. A quick solution is to
dynamically allocate using function malloc or realloc to create the
array. The maintenance involved in the dynamic memory manage can
become complex. To help reduce the complexity, I would suggest you
modify your datatype and write functions that you can use to
safely manipulate the datatype. Although I do not know the specific
purpose of your datatype, I have provided, below, an example that might
help you.

return 0;

} else return -1;
}

void saveDirectory () {
FILE *fdirectory = fopen (DIRECTORY_FILE, "wb");


.......snip.......
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define DIRECTORY_FILE "index.dat"

typedef struct
{
int local_depth;
int elements;
int address;
} table_element;

typedef struct
{
table_element *records;
unsigned global_depth;
} table_array;

/* Prototypes */
int loadDirectory(table_array *p);
int createArray(table_array *p, unsigned global_depth);
int saveDirectory (table_array *p);
void freeArray(table_array *p);
void printArray(table_array *p);

int main(void)
{
table_element test[4] = {{ 1,2,3},{2,3,4},{3,4,5},{6,7,8}};
table_array my = {NULL};
unsigned i,depth;

depth = 2;
if(!createArray(&my,depth)) exit(EXIT_FAILURE);
for(i = 0;i < (unsigned)pow(2,depth);i++)
my.records[i] = test[i];
printArray(&my);
if(saveDirectory(&my)) puts("\nSaving the array to file");
else
{
puts("\nFailure in saving the array to file");
exit(EXIT_FAILURE);
}
puts("\nFreeing the array\n");
freeArray(&my);
printArray(&my);
puts("\nloading the array from file\n");
if(loadDirectory(&my)) printArray(&my);
else puts("Failure in loading array from file");
freeArray(&my);
return 0;
}

int loadDirectory(table_array *p)
{
FILE *directoryFile = fopen (DIRECTORY_FILE, "rb");

if (directoryFile == NULL) return 0;
else
{
unsigned size,i;

freeArray(p);
if(1 != fread (&p->global_depth, sizeof (int), 1,
directoryFile))
{
freeArray(p);
return 0;
}
size = (unsigned)pow(2,p->global_depth);
p->records = malloc(size * (sizeof *p->records));
if(!p->records)
{
freeArray(p);
return 0;
}
for (i=0; i < size ; i++)
if(1 != fread(&p->records[i],sizeof(table_element),
1, directoryFile))
{
freeArray(p);
return 0;
}
}
fclose(directoryFile);
return 1;
}

int createArray(table_array *p, unsigned global_depth)
{
table_element *tmp;

if((tmp = realloc(p->records,
(size_t)pow(2,global_depth)*(sizeof *p->records))) == NULL)
return 0;
p->records = tmp;
p->global_depth = global_depth;
return 1;
}

int saveDirectory (table_array *p)
{
FILE *fdirectory = fopen (DIRECTORY_FILE, "wb");

if (fdirectory == NULL || p->global_depth == 0) return 0;
else
{
unsigned size;
if(1 != fwrite (&p->global_depth, sizeof (int),
1, fdirectory))
return 0;
size = (unsigned)pow(2,p->global_depth);
if(size != fwrite(p->records, sizeof(table_element),
size, fdirectory))
return 0;
fclose (fdirectory);
}
return 1;
}

void freeArray(table_array *p)
{
free(p->records);
p->records = NULL;
p->global_depth = 0;
return;
}

void printArray(table_array *p)
{
unsigned i;

if(p->global_depth == 0) puts("No Allocated Array");
else
{
for(i = 0;i < (unsigned)pow(2,p->global_depth);i++)
printf("Element #%u\n\tlocal_depth = %d\n\t"
"Elements = %d\n\tAddress = %d\n\n",
i+1,p->records[i].local_depth,
p->records[i].elements,p->records[i].address);
}
return;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4
On Sun, 06 Jun 2004 16:19:13 GMT, CBFalconer <cb********@yahoo.com>
wrote:
Jens Mittag wrote:

typedef struct {
int local_depth;
int elements;
int address;
} table_element;

table_element *records;
int global_depth;

int loadDirectory() {
FILE *directoryFile = fopen (DIRECTORY_FILE, "rb");

if (directoryFile != NULL) {
fread ( &global_depth, sizeof (int), 1, directoryFile);

printf ("Global Depth = %d\n", global_depth);

int size = (int) pow(2,global_depth);
More idiomatic, and probably more efficient: 1<<global_depth.
printf ("Size = %d\n", size);

table_element e[size];
table_element eintrag;
int i;


These declaration belong way up there, under FILE *... As it is
it should not even compile under any self-respecting C compiler.

They should under any C99; or gcc, which respects itself perhaps more
than it should. And if neither of those, then moving them is still
wrong as size is not a constant expression.
for (i=0; i < (int) pow(2,global_depth); i++) {
Since you've already computed 'size', (re)use it.
fread ( &eintrag, sizeof (table_element), 1, directoryFile);
printf ("I've read the following: Local-Depth = %d, Elements = %d, Address = %d\n", eintrag.local_depth, eintrag.elements, eintrag.address);
e[i] = eintrag;
}
Or, if you don't need the outputs, or can do them separately/later,
replace the whole loop by one
fread (e /* or records */, sizeof *e, size, directoryFile)
preferably with also
if( fread_as_above != size ) /* handle error appropriately */
records = e;


e is local. At function exit its contents are lost and its
address becomes meaningless.

Yep, that's the real killer.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: rob | last post by:
hey every1, I've got alot of data to write out to file and it's all just 1's and 0's. It's all stored in 2 dimensional arrays of width 32 and varying height. At the moment it's all just...
29
by: Glen | last post by:
Is it possible to write a structure to a file in c...as in c++...?? is it using fwrite?? thanx glen
5
by: Phil Kelly | last post by:
Hi I need to write the contents of a structure to a binary file - there is one string and 2 integers, but I can't seem to figure out how to write the data correctly. If I am simply writing...
2
by: twawsico | last post by:
I have a piece of code that needs to read the contents of a binary file (that I've created with another app) into an array of structures. The binary data in the file represents just a series of...
3
by: Zeke Zinzul | last post by:
Hi Guys & Geeks, What's the most elegant way of dealing with binary data and structures? Say I have this (which I actually do, a woo-hoo): struct Struct_IconHeader { byte width; byte...
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
6
by: John | last post by:
Hi I am trying to save settings of controls on my form to a file so I can read them back later and recreate the controls on the form. I have figured out how to go through all controls and get...
5
by: zehra.mb | last post by:
Hi, I had written application for storing employee data in binary file and reading those data from binary file and display it in C language. But I face some issue with writing data to binary file....
3
by: =?Utf-8?B?UmF5IE1pdGNoZWxs?= | last post by:
Hello, I'm trying to write an array of structures named myStructArray to a binary file and later on read it back. Although I could complete the entire project in C in about 2 minutes, I...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.