473,658 Members | 2,628 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing to an existing file.

Hi,

I want to open a binary file and write to a specific location in File.
Here is how my code looks like:

int main()
{

long lbuf = 0;
int lreadBytes = 0;
long lValue = 0;

FILE *pFile = fopen ("c:\\TestBin.b in","ab+");

fseek(pFile,4,S EEK_SET);

lValue = 222.4;

fwrite((char *)&lValue,1,siz eof(long),pFile );

fclose(pFile);
return 0;
}
This code writes to the end of file because I have opened it in append
mode. If I open in "wb+" mode the file gets erased. How do i write to
existing file?

Thanks and Regards,
Shal

Aug 1 '06 #1
6 2587
sh********@gmai l.com wrote:
Hi,

I want to open a binary file and write to a specific location in File.
Here is how my code looks like:

int main()
{

long lbuf = 0;
int lreadBytes = 0;
long lValue = 0;

FILE *pFile = fopen ("c:\\TestBin.b in","ab+");

fseek(pFile,4,S EEK_SET);

lValue = 222.4;

fwrite((char *)&lValue,1,siz eof(long),pFile );

fclose(pFile);
return 0;
}
This code writes to the end of file because I have opened it in append
mode. If I open in "wb+" mode the file gets erased. How do i write to
existing file?
"rb+". Your book should explain this.

Brian

Aug 1 '06 #2
sh********@gmai l.com writes:
I want to open a binary file and write to a specific location in File.
Here is how my code looks like:

int main()
{

long lbuf = 0;
int lreadBytes = 0;
long lValue = 0;

FILE *pFile = fopen ("c:\\TestBin.b in","ab+");

fseek(pFile,4,S EEK_SET);

lValue = 222.4;

fwrite((char *)&lValue,1,siz eof(long),pFile );

fclose(pFile);
return 0;
}
This code writes to the end of file because I have opened it in append
mode. If I open in "wb+" mode the file gets erased. How do i write to
existing file?
As Brian said, you're looking for "rb+".

A few other points:

You need "#include <stdio.h>".

"int main()" is acceptable, but "int main(void)" is better.

You declare lbuf and lreadBytes, but you never use them.

Always check the result of fopen().

The first argument to fwrite() is of type void*. Since any object
pointer type can be implicitly converted to void*, the cast to char*
is unnecessary. (It happens to be harmless, but it's clutter.)
I would write the fwrite call as:

fwrite(&lValue, 1, sizeof lValue, pFile);

And of course I'd check the result.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 1 '06 #3
Thanks for ur input. But there is a problem with using "rb+" mode.
If the file does not exist then I want it to be created and "rb+" will
not create a file.
How do i achieve this?
Default User wrote:
sh********@gmai l.com wrote:
Hi,

I want to open a binary file and write to a specific location in File.
Here is how my code looks like:

int main()
{

long lbuf = 0;
int lreadBytes = 0;
long lValue = 0;

FILE *pFile = fopen ("c:\\TestBin.b in","ab+");

fseek(pFile,4,S EEK_SET);

lValue = 222.4;

fwrite((char *)&lValue,1,siz eof(long),pFile );

fclose(pFile);
return 0;
}
This code writes to the end of file because I have opened it in append
mode. If I open in "wb+" mode the file gets erased. How do i write to
existing file?

"rb+". Your book should explain this.

Brian
Aug 3 '06 #4
In article <11************ **********@m79g 2000cwm.googleg roups.com>
<sh********@gma il.comwrote:
>Thanks for ur input.
Ur-input? That must be some sort of ancient prototype input
(see <http://dictionary.refe rence.com/search?q=ur>).
>But there is a problem with using "rb+" mode.
If the file does not exist then I want it to be created and "rb+" will
not create a file.
How do i achieve this?
There is the "portable method", and then there is the "good method".

The portable method is to use "w+". As you have seen, this wipes
out the existing file. So use it only if a first attempt with "r+"
fails.

This method is not "good" because there are all kinds of reasons
for "r+" to fail other than "file simply did not exist". Alas,
this is all you get in portable C. The "good" method -- along with
"how much better it is than the portable method" -- generally varies
from one system to another. This means that if you write code to
use this "better way", it will only work on a few systems, instead
of every hosted system.

It is up to you to decide whether the "good" method, whatever that
may be, is more important than the portability you lose by using
it.

(It would be nice if Standard C had a way to say "open file for
reading and writing, creating file if needed but not destroying
existing data if file already exists". But it does not, and
trying "r+" then "w+" is all we get in Standard C.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Aug 3 '06 #5

Keith Thompson wrote:
sh********@gmai l.com writes:
I want to open a binary file and write to a specific location in File.
Here is how my code looks like:
<snip>

fwrite((char *)&lValue,1,siz eof(long),pFile );
fwrite(&lValue, 1, sizeof lValue, pFile);
Ouch! I'd write it as:

fwrite(&lValue, sizeof lValue, 1, pFile);

Much less obscure, and easier to avoid a stupid mistake
when checking the return value.

Aug 4 '06 #6
"Bill Pursell" <bi**********@g mail.comwrites:
Keith Thompson wrote:
>sh********@gmai l.com writes:
I want to open a binary file and write to a specific location in File.
Here is how my code looks like:
<snip>
>
fwrite((char *)&lValue,1,siz eof(long),pFile );
> fwrite(&lValue, 1, sizeof lValue, pFile);

Ouch! I'd write it as:

fwrite(&lValue, sizeof lValue, 1, pFile);

Much less obscure, and easier to avoid a stupid mistake
when checking the return value.
Yes, you're right. The second and third parameters are the size in
bytes of a single element and the number of elements, respectively,
and the returned value is the number of elements successfully written.
I didn't bother to check the order.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 4 '06 #7

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

Similar topics

48
8470
by: Joseph | last post by:
Hi I'm writing a commercial program which must be reliable. It has to do some basic reading and writing to and from files on the hard disk, and also to a floppy. I have foreseen a potential problem. The program may crash unexpectedly while writing to the file. If so, my program should detect this during startup, and then (during startup) probably delete the data added to the file and redo the writing operation.
3
3648
by: Mahesha | last post by:
Hello, I'm new to C++ and I have requirement to open a existing text file in write mode and write 2 new lines of text in the beginning of the file. I'm working with fstream standard library. If someone could direct me to a sample code to do this that would be really helpful. Thanks, Mahesha
4
1808
by: Thierry Lam | last post by:
Let's say I already wrote a file and have the following: testing testing testing testing testing testing Is there an easy way to write something of variable length at the top of the file? For example,
10
52139
by: Aaron | last post by:
Hello, I have a small application that I need to save data from 7 text boxes in to a csv file. This will entail btnNext_Click function that will create a new csv file and enter the 7 data fields in the csv file; as well, each click on next will return carriage to a new line. Client does not what his data in an Access database(he hates Access with a passion)--he feels more comfortable with Excel. This data will be no greater than 1000...
2
6853
by: melanieab | last post by:
Hi, I'm trying to store all of my data into one file (there're about 140 things to keep track of). I have no problem reading a specific string from the array file, but I wasn't sure how to replace just one item. I know I can get the entire array, then save the whole thing (with a for loop and if statements so that the changed data will be saved), but it seems like a lot of unnecessary reading and writing. Is there a way to directly save...
2
6783
by: simonc | last post by:
Is there an easy way of writing a number in 32 bit integer format into four bytes of a file? I am experimenting with FilePut but I can only make it work by defining a four byte array and doing some simple calculations to work out from my integer what the individual values of the four bytes have to be. Surely there must be a short cut to doing this? And are there also any existing routines for converting a floating point number into...
1
1637
by: nasirmajor | last post by:
Dear all i have the following code for writing to the existing file. =========================== void AppendToFileEng() { SqlDataReader gr = null; string engpath2=""; gr = db.GetReader("Select * from tbl_SubCat2 Where SId2=" + SId2 + "");
5
11057
by: rasmitasah25 | last post by:
hi, I am very new to perl.I have written a perl script which is writing data into an excel file.The problem is that it is creating one new excel file while executing but my need id to write into an existing .xls file. currently I am using: my $workbook = Spreadsheet::WriteExcel::Big->new("file.xls"); for that which method Should I use?? can anyone please help me... Thanks
3
3775
by: thanawala27 | last post by:
Hi, I had problems writing in an existing Excel File. There is an excel file with a worksheet. I would like to open this existing Excel file and add another worksheet and write data into it. But I dont know how to open an existing excel file. can anyone give me some hint or help?
0
8850
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8746
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
8523
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
8626
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
7355
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...
0
4175
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4334
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2749
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 we have to send another system
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.