473,669 Members | 2,492 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 2615
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...@mindsp ring.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 <somethingNewTy peName;

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)? Misinterpretati on 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...@mindsp ring.comwrote:
>zaheer...@gmai l.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_FAILU RE);
}
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_FAILU RE);
}
if (fscanf(fp, "%d %d %d", &B.x, &B.y, &B.z) != 3) {
puts("fscanf problem");
fclose(fp);
exit(EXIT_FAILU RE);
}
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...@mindsp ring.comwrote:
>>zaheer...@gma il.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...@gmai l.com" <zaheer...@gmai l.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
5626
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 seems like someone was pulling my leg, because I really can't find anything about it. So, was I misinformed? Or perhaps this person was talking about some other classes you could use to do such a thing?
29
3563
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
7803
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 to pack the structure to 1 byte boundries, and then just write out the structure directly to the File IO function pragma pack (1 typedef struct char var1 int var1 }MyStruc fwrite(&myStructure,sizeof(MyStruct),1,filepointer);
2
1764
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 populating only the fields with value in specified locations(3 seperate structures). The way the C does is by creating a structures, which will be filled with null initially. Then selectivly populating only the fields with values and only up to the length...
5
4327
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 text to a file there is no problem - that starts when I attempt to write the structure. Can someone help me out, please?
1
2728
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
3442
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 I access the array elements. Thanks for your help. #include <stdio.h>
6
5262
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
1806
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
3806
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. Here is my part of my code. struct cust_data { int nCAFID; char *szFirstName;
0
8465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8809
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8588
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8658
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7407
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6210
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5682
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2032
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1788
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.