473,232 Members | 1,412 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,232 software developers and data experts.

Reading a Binary File....

HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
The file consists of structures of type----

struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}

I wrote a program which reads in these values into a structure which i
created in my program.While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......

My code is...

struct record{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};

struct record data;
FILE *file = fopen("db07", "rb");
while ( fread(&data, sizeof (struct record), 1, file) == 1 )
{
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}
Nov 19 '07 #1
13 3633
In <23**********************************@s36g2000prg. googlegroups.comswetha <la*******@gmail.comwrites:
I wrote a program which reads in these values into a structure which i
created in my program.While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......
Was the original datafile created on a different computer?

--
John Gordon A is for Amy, who fell down the stairs
go****@panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

Nov 19 '07 #2
swetha wrote:
HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
The file consists of structures of type----

struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}

I wrote a program which reads in these values into a structure which i
created in my program.While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......
[OP's code is at EOM]

/* You don't indicate how these files are created. In the example
* below I have added the writing of these files. Note that the
* structures in your file are not the same as those that you are using
* in your program. Also note that for 10-digit phone numbers (or
* 20-character names) your members name and phone are not strings,
* since they are not null terminated */

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

struct file_record
{
int acountnum;
char name[20];
float value;
char phone[10];
};

struct internal_record
{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};

void show_char_array(const char *label, size_t n, const char *s)
{
size_t i;
printf("%s:", label);
for (i = 0; i < n && s[i]; i++)
putchar(s[i]);
putchar('\n');
}

int main(void)
{
struct file_record make[3] = {
{1, "first guy", 72.3, "3123375032"},
{2, "second guy", 333.72, "2128836234"},
{3, "third guy", -62, "6182213"}
};
struct internal_record data;
FILE *file;
size_t written;

if (!(file = fopen("db07", "wb"))) {
fprintf(stderr, "could not open output file\n");
exit(EXIT_FAILURE);
}
written = fwrite(&make, sizeof *make, 3, file);
printf("%zu records written.\n", written);
fclose(file);

if (!(file = fopen("db07", "rb"))) {
fprintf(stderr, "could not open input file\n");
exit(EXIT_FAILURE);
}
printf("Note that the age member is not present in the input.\n"
"I have set it at 26\n\n");
data.age = 26;
while (fread(&data, sizeof *make, 1, file)) {
show_char_array("Name", 20, data.name);
printf("Account Number :%d\nAge:%d\n", data.acctnum, data.age);
show_char_array("Phone", 10, data.phone);
printf("Value:%f\n\n", data.value);
}
fclose(file);
remove("db07");
return 0;
}

[Output]
3 records written.
Note that the age member is not present in the input.
I have set it at 26

Name:first guy
Account Number :1
Age:26
Phone:3123375032
Value:72.300003

Name:second guy
Account Number :2
Age:26
Phone:2128836234
Value:333.720001

Name:third guy
Account Number :3
Age:26
Phone:6182213
Value:-62.000000
[OP's code]
>
My code is...

struct record{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};

struct record data;
FILE *file = fopen("db07", "rb");
while ( fread(&data, sizeof (struct record), 1, file) == 1 )
{
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}
Nov 19 '07 #3
swetha wrote On 11/19/07 16:24,:
HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
The file consists of structures of type----

struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}

I wrote a program which reads in these values into a structure which i
created in my program.While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......

My code is...

struct record{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};

struct record data;
FILE *file = fopen("db07", "rb");
while ( fread(&data, sizeof (struct record), 1, file) == 1 )
{
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}
Any of several things -- or a combination -- could be
the problem. Here are a few areas you should probably take
a look at:

1) Why does your program try to read an "age" element
that's not mentioned in your description of the file format?
If you read into a struct whose layout doesn't match that of
the file, you can't expect anything useful to happen.

2) Was the file written on a system compatible with the
one that's trying to read it? Systems differ in many ways,
such as the way numbers (int, float) are represented, the
amount and placement of padding within structs, and so on.
Padding differences would produce problems like those of (1),
and representation differences (e.g., "endianness") can be
even thornier: Something that means 123 to one machine might
easily mean -2231369728 to another.

3) The "name" and "phone" elements: Are all 20 or 10
characters actually present in the file, even if the strings
are as short as "Zaphod" and "n/a"? Or does the file hold
only the "significant" characters? (And see Martin Ambuhl's
warning about the possible non-string-ness of these items.)

A hex dump of the first couple hundred bytes of the file,
along with what they're "supposed to" represent and what you
actually get from your program, might be helpful.

--
Er*********@sun.com
Nov 19 '07 #4
On Nov 19, 5:00 pm, Martin Ambuhl <mamb...@earthlink.netwrote:
swetha wrote:
HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
The file consists of structures of type----
struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}
I wrote a program which reads in these values into a structure which i
created in my program.While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......

[OP's code is at EOM]

/* You don't indicate how these files are created. In the example
* below I have added the writing of these files. Note that the
* structures in your file are not the same as those that you are using
* in your program. Also note that for 10-digit phone numbers (or
* 20-character names) your members name and phone are not strings,
* since they are not null terminated */

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

struct file_record
{
int acountnum;
char name[20];
float value;
char phone[10];

};

struct internal_record
{
int acctnum;
char name[20];
float value;
char phone[10];
int age;

};

void show_char_array(const char *label, size_t n, const char *s)
{
size_t i;
printf("%s:", label);
for (i = 0; i < n && s[i]; i++)
putchar(s[i]);
putchar('\n');

}

int main(void)
{
struct file_record make[3] = {
{1, "first guy", 72.3, "3123375032"},
{2, "second guy", 333.72, "2128836234"},
{3, "third guy", -62, "6182213"}
};
struct internal_record data;
FILE *file;
size_t written;

if (!(file = fopen("db07", "wb"))) {
fprintf(stderr, "could not open output file\n");
exit(EXIT_FAILURE);
}
written = fwrite(&make, sizeof *make, 3, file);
printf("%zu records written.\n", written);
fclose(file);

if (!(file = fopen("db07", "rb"))) {
fprintf(stderr, "could not open input file\n");
exit(EXIT_FAILURE);
}
printf("Note that the age member is not present in the input.\n"
"I have set it at 26\n\n");
data.age = 26;
while (fread(&data, sizeof *make, 1, file)) {
show_char_array("Name", 20, data.name);
printf("Account Number :%d\nAge:%d\n", data.acctnum, data.age);
show_char_array("Phone", 10, data.phone);
printf("Value:%f\n\n", data.value);
}
fclose(file);
remove("db07");
return 0;

}

[Output]
3 records written.
Note that the age member is not present in the input.
I have set it at 26

Name:first guy
Account Number :1
Age:26
Phone:3123375032
Value:72.300003

Name:second guy
Account Number :2
Age:26
Phone:2128836234
Value:333.720001

Name:third guy
Account Number :3
Age:26
Phone:6182213
Value:-62.000000

[OP's code]


My code is...
struct record{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};
struct record data;
FILE *file = fopen("db07", "rb");
while ( fread(&data, sizeof (struct record), 1, file) == 1 )
{
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -
Hi.....actually i have forgot age in the previous structre...age is
present in both....and there is no need to put data into that
file.....already i have a file which consists of data in the binary
format.....i wanted to read that data ...while doing so i could easily
i could retrieve the char values correctly but i have a problem with
the float and int values .....for float and int what should i do ???
i dont have any idea wher that file is from ..is ther a way to know
that ???
Nov 19 '07 #5
swetha <la*******@gmail.comwrites:
On Nov 19, 5:00 pm, Martin Ambuhl <mamb...@earthlink.netwrote:
>swetha wrote:
HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
The file consists of structures of type----
struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}
>.i wanted to read that data ...while doing so i could easily
i could retrieve the char values correctly but i have a problem with
the float and int values .....for float and int what should i do ???
i dont have any idea wher that file is from ..is ther a way to know
that ???
You need to look at the data and see what format it is in. A hex dump
program like od or hd (on *nix systems) will show you exactly what is
in the file. There are so many possible formats that guessing is
probably pointless. Posting a small extract in hex somewhere topical
(maybe comp.programming) might help.

--
Ben.
Nov 20 '07 #6
In article
<23**********************************@s36g2000prg. googlegroups.com>,
swetha <la*******@gmail.comwrote on Tuesday 20 Nov 2007 2:54 am:
HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
If this file has been created on a different system to the one in which
it is being read, or if a different program has created it than the one
doing the reading, or if your program does not know the exact details
of the file's format, subtle errors may occur.

This is why it is often better to deal with text files unless there are
compelling reasons for doing otherwise. For many programs on modern
desktop systems, which need not be performance critical, it is just
fine to store data in text files.
The file consists of structures of type----

struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}
You are missing a semi-colon to terminate the structure declaration.
Please copy and paste code. Retyping has been proven, time and again,
to result in annoying typos and incomplete code.
I wrote a program which reads in these values into a structure which i
created in my program. While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......

My code is...

struct record{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};
Which structure is the one you are actually using? This one or the one
previous? This once again illustrates why code should be, wherever
possible, cut and pasted.
struct record data;
FILE *file = fopen("db07", "rb");
You might use a name other than 'file' for readability reasons. Have two
identifiers differring only in case, though legal in C, is not a very
good programming practise. And it might lead to conflicts if the
identifiers happen to have external linkage _and_ you happen to use a
very old or primitive linker. Better to be safe and avoid the
possibility altogether.
while ( fread(&data, sizeof (struct record), 1, file) == 1 )
{
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}
A likely possibility is that the data file was created on a system other
than the one it is under now, or that it was created by a program
compiled with certain compiler options that this program (i.e., the one
reading the file) has not taken into account.

If it is indeed one of these possibilities then you need to know the
exact layout of the file's structure objects before you can read it in
correctly.

Nov 20 '07 #7

swetha wrote:
HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
The file consists of structures of type----

struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}

I wrote a program which reads in these values into a structure which i
created in my program.While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......

My code is...

struct record{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};

struct record data;
FILE *file = fopen("db07", "rb");
while ( fread(&data, sizeof (struct record), 1, file) == 1 )
{
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}
You should be using write to output binary values. printf converts the
output to characters.

--
Bill C.
Nov 21 '07 #8
swetha wrote:
) I wrote a program which reads in these values into a structure which i
) created in my program.While printing the values i got the "name" and
) "phone" values correctly ( as they are in char) ....but iam not
) getting the accountnum and value fields.Iam getting some arbitary
) values.SO can any1 help me out in this of how to retrieve the values
) correctly ......
)
) My code is...
)
) struct record{
) int acctnum;
) char name[20];
) float value;
) char phone[10];
) int age;
) };
)
) struct record data;
) FILE *file = fopen("db07", "rb");
) while ( fread(&data, sizeof (struct record), 1, file) == 1 )
) {
) printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
) data.name, data.acctnum,data.age,data.phone,data.value);
) }

In C, a struct might be padded. That is, there may be some empty space
between, say, 'name' and 'value'. If you want maximal robustness in
reading a file, you should be reading it element by element instead.

Also, and presumably the cause of your problem, there could be an endianess
issue. Can you give some examples of expected and actual values ?
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Nov 21 '07 #9
spacecriter (Bill C) wrote:
[...]
You should be using write to output binary values. printf converts the
output to characters.
You probably mean (or you *should* mean) fwrite rather than write. The
write function is non-standard (it's defined by POSIX, not by the C
standard).

Both fwrite and printf are defined in terms of character output. It
*usually* makes more sense to use fwrite for binary files and printf (or
fputs, etc) for text files, but both will work equally well for either
text or binary.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 21 '07 #10
On Nov 22, 12:52 pm, Keith Thompson <ks...@mib.orgwrote:
Both fwrite and printf are defined in terms of character output. It
*usually* makes more sense to use fwrite for binary files and printf (or
fputs, etc) for text files, but both will work equally well for either
text or binary.
If you have a block of "binary data", that could contain
null characters, then the printf family isn't a suitable
choice for output.

Nov 22 '07 #11
"spacecriter (Bill C)" wrote:
swetha wrote:
.... snip ...
>>
struct record data;
FILE *file = fopen("db07", "rb");
while ( fread(&data, sizeof (struct record), 1, file) == 1 ) {
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}

You should be using write to output binary values. printf
converts the output to characters.
Why? He is simply making the output legible on other systems.
Text is portable, binary isn't.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 22 '07 #12
Old Wolf wrote:
On Nov 22, 12:52 pm, Keith Thompson <ks...@mib.orgwrote:
>Both fwrite and printf are defined in terms of character output. It
*usually* makes more sense to use fwrite for binary files and printf (or
fputs, etc) for text files, but both will work equally well for either
text or binary.

If you have a block of "binary data", that could contain
null characters, then the printf family isn't a suitable
choice for output.
Not if you use the "%s" format, but this:
printf("%c", '\0');
is well defined.

But you're right, printf wouldn't be a *suitable* choice, even though you could
make it work with some effort.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 22 '07 #13
On Wed, 21 Nov 2007 12:44:19 -0500, "spacecriter \(Bill C\)"
<sp*********@sysmatrix.net.yercrankwrote:
>
swetha wrote:
>HI Every1,
I have a problem in reading a binary file.
Actually i want a C program which reads in the data from a file which
is in binary format and i want to update values in it.
The file consists of structures of type----

struct record {
int acountnum;
char name[20];
float value;
char phone[10];
}

I wrote a program which reads in these values into a structure which i
created in my program.While printing the values i got the "name" and
"phone" values correctly ( as they are in char) ....but iam not
getting the accountnum and value fields.Iam getting some arbitary
values.SO can any1 help me out in this of how to retrieve the values
correctly ......

My code is...

struct record{
int acctnum;
char name[20];
float value;
char phone[10];
int age;
};

struct record data;
FILE *file = fopen("db07", "rb");
while ( fread(&data, sizeof (struct record), 1, file) == 1 )
{
printf("Name:%s\nAccount Number :%d\nAge:%d\nPhone:%s\nValue:%f\n",
data.name, data.acctnum,data.age,data.phone,data.value);
}

You should be using write to output binary values. printf converts the
output to characters.
He is not using printf to output binary values. He is using it to
print data (suitably converted to readable characters) that he read
from a binary file.

Since write is not part of the standard library, fwrite would be a
better recommendation in this group if he wanted to output binary
data.
Remove del for email
Nov 22 '07 #14

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

Similar topics

4
by: john smith | last post by:
Hi, I have a file format that is going to contain some parts in ascii, and some parts with raw binary data. Should I open this file with ios::bin or no? For example: filename: a.bin number of...
20
by: ishmael4 | last post by:
hello everyone! i have a problem with reading from binary file. i was googling and searching, but i just cant understand, why isnt this code working. i could use any help. here's the source code:...
6
by: KevinD | last post by:
assumption: I am new to C and old to COBOL I have been reading a lot (self teaching) but something is not sinking in with respect to reading a simple file - one record at a time. Using C, I am...
50
by: Michael Mair | last post by:
Cheerio, I would appreciate opinions on the following: Given the task to read a _complete_ text file into a string: What is the "best" way to do it? Handling the buffer is not the problem...
7
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should...
30
by: siliconwafer | last post by:
Hi All, I want to know tht how can one Stop reading a file in C (e.g a Hex file)with no 'EOF'?
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;
9
by: Use*n*x | last post by:
Hello, I have a binary file (image file) and am reading 4-bytes at a time. The File size is 63,480,320 bytes. My assumption is that if I loop through this file reading 4 bytes at a time, I...
3
by: The Cool Giraffe | last post by:
Regarding the following code i have a problem. void read () { fstream file; ios::open_mode opMode = ios::in; file.open ("some.txt", opMode); char *ch = new char; vector <charv; while...
6
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.