473,406 Members | 2,377 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,406 software developers and data experts.

Read/Write to file

Hello!

I need some help/recommendations on how to do the following.
I have a program that writes an IP address two control numbers and a
date to file, on one line. It's a basic text file and it looks like this:

----- beginning of file -----
192.168.0.1 0 0 2004-08-01
192.168.0.2 1 0 2004-08-21
192.168.0.4 0 1 2004-08-12
-------- end of file --------

I know how to write data to a file. But what if I want to change data in
this file, for instance, on line two I want to change the first control
number to a 0 instead of a 1. How would I do this?

Thank you for an honest answer.

Best regards
Martin
Nov 14 '05 #1
5 3142
Martin Svensson <sk******@be-openminded.com> wrote:
I need some help/recommendations on how to do the following.
I have a program that writes an IP address two control numbers and a
date to file, on one line. It's a basic text file and it looks like this: ----- beginning of file -----
192.168.0.1 0 0 2004-08-01
192.168.0.2 1 0 2004-08-21
192.168.0.4 0 1 2004-08-12
-------- end of file -------- I know how to write data to a file. But what if I want to change data in
this file, for instance, on line two I want to change the first control
number to a 0 instead of a 1. How would I do this?


As long as you don't want to insert something into the file but just
overwrite parts of it it's rather simple, the following should do
that (assuming the file is names "data.txt" and leaving out all the
checks you _should_ do):

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

int main( void )
{
FILE *fp = fopen( "data.txt", "rb+" );

while ( fgetc( fp ) != '\n' ) /* go to start of 2nd line */
/* empty */ ;
fseek( fp, 12, SEEK_CUR ); /* go to char to be changed */
fprintf( fp, "0" );
fclose( fp );
return EXIT_SUCCESS;
}

What you can't do is inserting more data then are already there, in
that case you would have to create a new file, copying everything
you want to keep and interspersed with the changes.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #2
Martin Svensson wrote:
Hello!

I need some help/recommendations on how to do the following.
I have a program that writes an IP address two control numbers and a
date to file, on one line. It's a basic text file and it looks like this:

----- beginning of file -----
192.168.0.1 0 0 2004-08-01
192.168.0.2 1 0 2004-08-21
192.168.0.4 0 1 2004-08-12
-------- end of file --------

I know how to write data to a file. But what if I want to change data in
this file, for instance, on line two I want to change the first control
number to a 0 instead of a 1. How would I do this?
Open the file for update ("r+" mode), read all the
data up to but not including the '0' you want to change,
do an fseek(stream, 0, SEEK_CUR), and then write the '1'.
(The fseek() looks like a no-op, but you must do a file-
positioning operation when changing from input to output.)

*However*, this technique relies on the fact that '0'
and '1' are the same length. If you wanted to change the
0 to 12345 (or change 12345 to 0) this wouldn't work because
all the remaining characters in the file would need to
"slide over" to accommodate the change in length. Such
things can be done, but they are not easy. Two other
possibilities:

- Instead of trying to update the file "in place,"
consider reading the old file and writing a new
one with updated information. Just copy data from
the old file to the new, but whenever you recognize
a line that you want to change, write out the new
version instead of the old. This technique works
best if you can "batch" many changes together and
do them all in one pass over the data.

- If the order of lines in the file is not important,
you can "replace" a short line with a longer one
by (1) marking the original as "ignore me" by
changing its first character to 'x' or something
else that can't occur in valid data, and (2) writing
the new version of the line at the end of the file.
When reading the file in some other program, ignore
any line that begins with 'x'.

There are fancier schemes, too, but I can't tell from
your description whether they'd be worth while.
Thank you for an honest answer.


I always lie.

--
Er*********@sun.com

Nov 14 '05 #3
Martin Svensson wrote on 11/08/04 :
I have a program that writes an IP address two control numbers and a date to
file, on one line. It's a basic text file and it looks like this:

----- beginning of file -----
192.168.0.1 0 0 2004-08-01
192.168.0.2 1 0 2004-08-21
192.168.0.4 0 1 2004-08-12
-------- end of file --------

I know how to write data to a file. But what if I want to change data in this
file, for instance, on line two I want to change the first control number to
a 0 instead of a 1. How would I do this?

Thank you for an honest answer.


I'm not sure what an 'honest' answer is, but here is mine:

- The brute force: Use a text editor. Period.

- The C-force: you need two files. One on read text mode, one on write
text mode. You read the original, line by line. You check the line and
copy them unchanged or not according to your will. he line being just
another array of char, replacing a character by another one is trivial.

Of course, you need the FILE functions declared in <stdio.h> (fopen(),
fgets(), fputs(), fclose() etc.).

Then you can smartly use rename() and remove() to get a new file with
the old name, and eventually the n-1 version of the file for undo (.bak
or whatever).

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html

"C is a sharp tool"

Nov 14 '05 #4
Thank you very much, it worked just fine. I need to figure out what
method I will use, read from one file and write to another or have the
whole data in one file and just replace characters. Let's say I have all
the data in one file. For example a whole IP scoop in the same format as
my first example. How do I search the file for let's say and IP address
and find out what line number it's at? And how do I go to that line
before I'll write data to the file? I can't find such information in the
man files for fseek or any other file function.

Help is much appriciated!
Thank you once again for the great example!

Martin

Je***********@physik.fu-berlin.de wrote:
Martin Svensson <sk******@be-openminded.com> wrote:
I need some help/recommendations on how to do the following.
I have a program that writes an IP address two control numbers and a
date to file, on one line. It's a basic text file and it looks like this:


----- beginning of file -----
192.168.0.1 0 0 2004-08-01
192.168.0.2 1 0 2004-08-21
192.168.0.4 0 1 2004-08-12
-------- end of file --------


I know how to write data to a file. But what if I want to change data in
this file, for instance, on line two I want to change the first control
number to a 0 instead of a 1. How would I do this?

As long as you don't want to insert something into the file but just
overwrite parts of it it's rather simple, the following should do
that (assuming the file is names "data.txt" and leaving out all the
checks you _should_ do):

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

int main( void )
{
FILE *fp = fopen( "data.txt", "rb+" );

while ( fgetc( fp ) != '\n' ) /* go to start of 2nd line */
/* empty */ ;
fseek( fp, 12, SEEK_CUR ); /* go to char to be changed */
fprintf( fp, "0" );
fclose( fp );
return EXIT_SUCCESS;
}

What you can't do is inserting more data then are already there, in
that case you would have to create a new file, copying everything
you want to keep and interspersed with the changes.

Regards, Jens

Nov 14 '05 #5
Martin Svensson <sk******@be-openminded.com> wrote:
Thank you very much, it worked just fine. I need to figure out what
method I will use, read from one file and write to another or have the
whole data in one file and just replace characters. Let's say I have all
Well, Eric Sosman pointed out that you can also "insert" into a
file (but typically it's not trivial and simply writing to a new
file and then replacing the old one with it tends to be simpler).
the data in one file. For example a whole IP scoop in the same format as
my first example. How do I search the file for let's say and IP address
and find out what line number it's at? And how do I go to that line
before I'll write data to the file? I can't find such information in the
man files for fseek or any other file function.


You will probably have to do that manually, i.e. reading in lines,
counting them and the number of characters in them and use string
comparison functions to find out if the IP address you're looking
for is on that line. Assuming no further complications (i.e. lines
that are longer than the buffer you use for reading in lines) some-
thing like the following should do the trick (but take care, it's
completely untested):

#define MAX_LINE_LEN 4096 /* must be longer than longest input line! */

int ip_replace( FILE *fp, const char* old_ip, const char *new_ip )
{
long cur_pos = 0;
char buf[ MAX_LINE_LEN ];
char *where;

if ( strlen( old_ip ) != strlen( new_ip ) ) /* can we replace? */
return 1;
rewind( fp );
while ( fgets( buf, MAX_LINE_LEN, fp ) != NULL ) {
if ( ( where = strstr( buf, old_ip ) ) == NULL ) {
cur_pos += strlen( buf );
continue;
}
if ( fseek( fp, cur_pos + where - buf, SEEK_SET ) != 0 ||
fprintf( fp, "%s", new_ip ) != 1 )
break;
return 0;
}
return 1;
}

The function returns 0 if the replacement in the file of 'old_ip' by
'new_ip' was successful and 1 on all kinds of failures. I didn't
bother with line numbers here, but it's trivial to add a variable
for the line count and increment it after each successful fgets().

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #6

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

Similar topics

22
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; ...
1
by: Magix | last post by:
Hi, I have these string data: str_data1, str_data2, str_data3, which capture some value after a routine process A. Then I would like to write (append) these 3 string values into a text file each...
5
by: Just Me | last post by:
Using streams how do I write and then read a set of variables? For example, suppose I want to write into a text file: string1,string2,string3 Then read them later. Suppose I want to write...
8
by: a | last post by:
I have a struct to write to a file struct _structA{ long x; int y; float z; } struct _structA A; //file open write(fd,A,sizeof(_structA)); //file close
5
by: Sumana | last post by:
Hi All, We developed our project on VC++.Net console application to create image of disk and to write the image We are having problem with reading and writing the sector beyond 6GB Disk or...
3
by: nicolasg | last post by:
Hi, I'm trying to open a file (any file) in binary mode and save it inside a new text file. After that I want to read the source from the text file and save it back to the disk with its...
2
by: agphoto | last post by:
There is big or problem in open file in read and write mode.. $file = "data.txt"; $fp = fopen($file,"w+"); $line = fgets($fp,"120"); // i need only 1st line to read and upto 120 bytes echo...
2
by: Kevin Ar18 | last post by:
I posted this on the forum, but nobody seems to know the solution: http://python-forum.org/py/viewtopic.php?t=5230 I have a zip file that is several GB in size, and one of the files inside of it...
9
by: vineeth | last post by:
Hello all, I have come across a weird problem, I need to determine the amount of bytes read from a file, but couldn't figure it out , My program does this : __ file = open("somefile") data =...
1
by: Sachin Garg | last post by:
I have a program which opens a fstream in binary input+output mode, creating the file if it doesn't exists. But writing doesn't works after reading, it must be something obvious that I am not aware...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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
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...
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,...

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.