473,508 Members | 2,330 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing a structure into a file

I am using the following code

typedef struct A {
int x;
int y;
int z;
};

int main(void) {

struct A A;
struct A B;
FILE *fp;
A.x = 80000;
A.y = 40000;
A.z = 12345;

printf("%d %d %d\n", A.x, A.y, A.z);
fp = fopen("file.txt", "wb");
fwrite(&A, sizeof A, 3, fp);
fclose(fp);
fp = fopen("file.txt", "rb");
fread(&B, sizeof B, 1, fp);
fclose(fp);
printf("%d %d %d\n", B.x, B.y, B.z);
return 0;
}
But the file.txt is containing junk values when i open it . Please let
me know what is wrong in my program.

Thanks,
Zaheer
Jun 27 '08 #1
8 2597
za*******@gmail.com wrote:
I am using the following code

Don't forget <stdio.h>
typedef struct A {
struct A A;
struct A B;
fwrite(&A, sizeof A, 3, fp);
What's the (3) for?
You don't have three A's

fread(&B, sizeof B, 1, fp);
But the file.txt is containing junk values when i open it . Please let
me know what is wrong in my program.

--
pete
Jun 27 '08 #2
On Jun 24, 7:36 pm, pete <pfil...@mindspring.comwrote:
zaheer...@gmail.com wrote:
I am using the following code

Don't forget <stdio.h>
typedef struct A {
struct A A;
struct A B;
fwrite(&A, sizeof A, 3, fp);

What's the (3) for?
You don't have three A's
fread(&B, sizeof B, 1, fp);
But the file.txt is containing junk values when i open it . Please let
me know what is wrong in my program.

--
pete
Sorry for that it should have been 1
Jun 27 '08 #3
za*******@gmail.com wrote:
I am using the following code

typedef struct A {
int x;
int y;
int z;
};
Either provide a name for the "new type", or (better, I think) don't
typedef.

typedef <somethingNewTypeName;

Your <somethingis the whole struct A above. You do not have a name
for the 'new type'.
My compiler emitted a warning for the construction without a name for
the typedef:
"warning: useless storage class specifier in empty declaration"

After removing the typedef, keeping only "struct A { ... }" and
#includeing <stdio.h>, the compilation worked fine and the program
output was the expected one ... but see below
int main(void) {

struct A A;
struct A B;
FILE *fp;
A.x = 80000;
A.y = 40000;
A.z = 12345;

printf("%d %d %d\n", A.x, A.y, A.z);
fp = fopen("file.txt", "wb");
What if "file.txt" cannot be opened? You should test fp.
if (fp == NULL) { /* file.txt could not be opened for writing */ }
fwrite(&A, sizeof A, 3, fp);
Now you're trying to access 3 elements of size "sizeof A".
You have no guarantee that the second element (or the third) can be
read.
fclose(fp);
fp = fopen("file.txt", "rb");
Verify that the fopen() call didn't fail.
fread(&B, sizeof B, 1, fp);
fclose(fp);
printf("%d %d %d\n", B.x, B.y, B.z);
return 0;
}
But the file.txt is containing junk values when i open it .
What do you mean 'junk values'?
If your program didn't fail at writing 3 (inexistent) elements at the
fwrite() call, file.txt will have 3 * sizeof(struct A) bytes.
On my computer that is 3 * 12 bytes = 36 bytes.
ON MY COMPUTER, the first 12 bytes of the file correspond to the
members x, y, and z.
I have absolutely no idea what the other 24 bytes are.
Please let me know what is wrong in my program.
1) Failure to #include <stdio.h>
2) accessing inexistent data
3) writing more than you'd like to the file
4)? Misinterpretation of 'junk values'?

Why don't you write to the file in text mode using fprintf? and read
with fgets()?

fprintf(fp, "struct A: x = %d; y = %d; z = %d\n", A.x, A.y, A.z);

and

#define MAXLINE_LENGTH 80

char buf[MAXLINE_LENGTH];

if (fgets(buf, sizeof buf, fp) != NULL) {
/* parse buf to extract B.x, B.y, and B.z */
}
Jun 27 '08 #4
za*******@gmail.com wrote:
On Jun 24, 7:36 pm, pete <pfil...@mindspring.comwrote:
>zaheer...@gmail.com wrote:
>>I am using the following code
Don't forget <stdio.h>
>>typedef struct A {
struct A A;
struct A B;
fwrite(&A, sizeof A, 3, fp);
What's the (3) for?
You don't have three A's
>>fread(&B, sizeof B, 1, fp);
But the file.txt is containing junk values when i open it . Please let
me know what is wrong in my program.
--
pete

Sorry for that it should have been 1
My second problem is that this is the output on my machine:

C:\Program Files\DevStudio\SharedIDE\bin\Debug>new
80000 40000 12345
80000 40000 12345

C:\Program Files\DevStudio\SharedIDE\bin\Debug>

Intermittent problems tend to be a little tougher to diagnose.

I convert the program to a correct C program and see what turns up.

--
pete
Jun 27 '08 #5
ba******@gmail.com wrote:
za*******@gmail.com wrote:
>fp = fopen("file.txt", "rb");
Why don't you write to the file in text mode
That's the first thing that popped into my mind.

/* BEGIN new.c */

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

int main(void)
{
struct A {
int x;
int y;
int z;
};
struct A A;
struct A B = {0};
FILE *fp;

A.x = 80000;
A.y = 40000;
A.z = 12345;
printf("%d %d %d\n", A.x, A.y, A.z);
fp = fopen("file.txt", "w");
if (fp == NULL) {
puts("fp == NULL #1");
exit(EXIT_FAILURE);
}
fprintf(fp, "%d %d %d\n", A.x, A.y, A.z);
fclose(fp);
fp = fopen("file.txt", "r");
if (fp == NULL) {
puts("fp == NULL #2");
exit(EXIT_FAILURE);
}
if (fscanf(fp, "%d %d %d", &B.x, &B.y, &B.z) != 3) {
puts("fscanf problem");
fclose(fp);
exit(EXIT_FAILURE);
}
fclose(fp);
printf("%d %d %d\n", B.x, B.y, B.z);
return 0;
}

/* END new.c */

--
pete
Jun 27 '08 #6
za*******@gmail.com wrote:
I am using the following code

typedef struct A {
int x;
int y;
int z;
};

int main(void) {

struct A A;
struct A B;
FILE *fp;
This indicates that you've included <stdio.h>, which is a
good thing, but that you've omitted the inclusion from what
you've posted. What else did you leave out? Is the code I'm
trying to debug in any way to the code that's actually giving
you problems?
A.x = 80000;
A.y = 40000;
A.z = 12345;

printf("%d %d %d\n", A.x, A.y, A.z);
fp = fopen("file.txt", "wb");
Did the fopen() call succeed? Probably, or you'd most
likely see a different sort of error. Still, it *never* hurts
to check.
fwrite(&A, sizeof A, 3, fp);
Even under the most favorable of circumstances, your program
goes off the rails here and its behavior becomes unpredictable.
You have asked fwrite() to output the contents of three consecutive
`struct A' instances, but only one instance exists at the memory
location you've indicated. When fwrite() trustingly tries to output
the other two, anything can happen.

Oh, yes: Did the fwrite() succeed or fail, or succeed partially?
Again, it wouldn't hurt to check ...
fclose(fp);
Success? Failure?
fp = fopen("file.txt", "rb");
Success? Failure?
fread(&B, sizeof B, 1, fp);
Success? Failure? This time, at least, you're not asking for
more data than you've got memory to store it in.
fclose(fp);
printf("%d %d %d\n", B.x, B.y, B.z);
return 0;
}
But the file.txt is containing junk values when i open it . Please let
me know what is wrong in my program.
Fix the obvious blunder in fwrite(), add success/failure
checks, re-run, and come back again if you're still having
trouble.

--
Er*********@sun.com
Jun 27 '08 #7
pete wrote:
za*******@gmail.com wrote:
>On Jun 24, 7:36 pm, pete <pfil...@mindspring.comwrote:
>>zaheer...@gmail.com wrote:
I am using the following code
Don't forget <stdio.h>

typedef struct A {
struct A A;
struct A B;
fwrite(&A, sizeof A, 3, fp);
What's the (3) for?
You don't have three A's

fread(&B, sizeof B, 1, fp);
But the file.txt is containing junk values when i open it . Please let
me know what is wrong in my program.
--
pete

Sorry for that it should have been 1

My second problem is that this is the output on my machine:

C:\Program Files\DevStudio\SharedIDE\bin\Debug>new
80000 40000 12345
80000 40000 12345
Is it the case that by "when i open it"
you are referring to a text editor,
and not the output of your program?

If so, then that's kind of what binary mode is all about.
There's no way that only knowing this program's source code,
will tell you which bytes are going to wind up in that file.

--
pete
Jun 27 '08 #8
On Jun 24, 7:13 pm, "zaheer...@gmail.com" <zaheer...@gmail.comwrote:
But the file.txt is containing junk values when i open it . Please let
me know what is wrong in my program.
with stdio.h included, I am getting the output you expected.
80000 40000 12345
80000 40000 12345
Your issue is already addressed. Your code appears to be broken in
more than one ways but the issue of seeing junk is that you are using
a text editor to analyze the file. Use a binary/hexadecimal editor and
you can check that you are getting the right values and some junk
because of your 3 in fwrite. (If you haven't used any binary/hex
editor, it will be all greek and latin with all the endian-ness and
stuff to worry about)

My compiler warns about your typedef:

bin.c:10: warning: useless storage class specifier in empty
declaration

Using a static code checker can let you know other issues which you
are ignoring ( not checking the return value for fopen, fread, fwrite
etc). In my case, lint has got this to say.

Splint 3.1.1 --- 19 Jul 2006

bin.c: (in function main)
bin.c:25:28: Possibly null storage fp passed as non-null param:
fwrite (..., fp)
A possibly null pointer is passed as a parameter corresponding to a
formal
parameter with no /*@null@*/ annotation. If NULL may be used for
this
parameter, add a /*@null@*/ annotation to the function parameter
declaration.
(Use -nullpass to inhibit warning)
bin.c:24:8: Storage fp may become null
bin.c:25:3: Return value (type size_t) ignored: fwrite(&A, sizeo...
Result returned by function call is not used. If this is intended,
can cast
result to (void) to eliminate message. (Use -retvalother to inhibit
warning)
bin.c:26:3: Return value (type int) ignored: fclose(fp)
Result returned by function call is not used. If this is intended,
can cast
result to (void) to eliminate message. (Use -retvalint to inhibit
warning)
bin.c:28:27: Possibly null storage fp passed as non-null param: fread
(..., fp)
bin.c:27:8: Storage fp may become null
bin.c:28:3: Return value (type size_t) ignored: fread(&B, sizeof...
bin.c:29:3: Return value (type int) ignored: fclose(fp)
lint is not related to the language C, but the output I have posted is
related to your C problem.

Jun 27 '08 #9

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

Similar topics

6
5619
by: DanielEKFA | last post by:
Hey there :) I was once told that the STL classes had member functions to write their data to disk and to restore that data. Searching google (and why are there no "stl" or "map" manpages?), it...
29
3530
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
2
7793
by: phyzics | last post by:
I am porting an application from C++ to C#, and am having trouble finding a way to quickly and efficiently write structures to a binary file. In C++ this is trivial because all that is necessary is...
2
1740
by: DBC User | last post by:
Hi Sharpies, I have a C program I am converting it into C#. Everything is fine except this process creates a 6K byte binary file. This file initially filled with 6K null and then start...
5
4318
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...
1
2718
by: RML | last post by:
Hi, I have a MFC C++ application which write the data in a structure out to a file. Here is the structure... typdef struct { short ID; TCHAR Num; short x; } TestStruct;
8
3434
by: SP | last post by:
The following code crashes after I add the two nested FOR loops at the end, I am starting to learn about pointers and would like to understand what I'm doing wrong. I think the problem is the way...
6
5244
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;
4
1790
by: prashant.khade1623 | last post by:
Hi I am trying ti write a structure to a file, but I am getting segmentation fault. Below is my program #include<stdio.h> main() { FILE *fp; struct student {
5
3794
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....
0
7135
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
7410
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
7505
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...
1
5060
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4729
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
3215
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
1570
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 ...
1
774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
440
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.