473,902 Members | 4,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replace word in text file

Hello, I need to write a program that opens a text file and scans the entire
file for a specific line and when that line is found, a particular word on
that line is to be replaced. The new word is given as an argument to the
program. I wrote a small test program that doesn't work because strcmp()
fails to find a matching line. Here's the code:

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv)
{
FILE* in_file = NULL;
FILE* out_file = NULL;
char* temporary_file_ name = NULL;
char line[128];

if(argc < 2)
{
fprintf(stderr, "You must supply a word.\n");

return 1;
}

in_file = fopen("test.txt ", "r");

if(in_file == NULL)
{
fprintf(stderr, "Error opening test.txt\n");

return 1;
}

temporary_file_ name = tmpnam(NULL);

out_file = fopen(temporary _file_name, "w");

while(fgets(lin e, sizeof(line), in_file))
{
printf("Line read: %s\n", line);

if(strcmp(line, "set imap_user=root" ) == 0)
{
printf("Replaci ng.\n");
strcpy(line, "set imap_user=");
strcat(line, argv[1]);
}

fputs(line, out_file);
}

fclose(in_file) ;
fflush(out_file );
fclose(out_file );

remove("test.tx t");
rename(temporar y_file_name, "test.txt") ;

return 0;
}

And here's the original file test.txt:
set spoolfile=imap://sysinst.ida.liu .se/INBOX
set folder=imap://sysinst.ida.liu .se/INBOX
set imap_user=root
set ssl_starttls=no
set sendmail="/usr/sbin/sendmail -oem -oi"

Why doesn't it work?

/ William Payne
Nov 13 '05
18 22024
Ed Morton <mo************ ****@lucent.com > wrote:

On 11/5/2003 3:25 PM, William Payne wrote:
<snip>
But strcmp() never returns 0 so no replacement is made. So then I tried
replacing the call to strcmp() with the following:
if(strstr(line, "set imap_user=root" ) != NULL)

and now it founds a match one the correct line and correctly replaces the
word. Very good, but it annoys me that I don't know why strcmp() doesn't
work.
See my previous response. This should work for you: while(fgets(lin e, sizeof(line), in_file))
{
printf("Line read: %s\n", line); if(strncmp(line , "set imap_user=root" , sizeof "set imap_user=root" - 1 ) =
= 0)
{ i.e. just compare the number of chars that you want to match, ignoring any
new-line characters from the input file so your code isn't dependent on the
OS/tool that produced the input file. In your final code, you'll probably want
to define a string constant or macro for "set imap_user=root" rather than
hard-coding it twice, but you get the idea. You should probably also add a
"strlen" check to ensure that line isn't actually longer than you expected (e.g.
"set imap_user=rootc rop") Ed.


Another thing that could go wrong is that what looks like a space
character is in reality a tab character, so you may have to check
with

if ( strncmp( line, "set imap_user=root" ,
sizeof "set imap_user=root" - 1 ) == 0 ||
strncmp( line, "set\timap_user =root",
sizeof "set\timap_user =root" - 1 ) == 0 )

for both cases.
Regards, Jens
--
_ _____ _____
| ||_ _||_ _| Je***********@p hysik.fu-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oe rring
Nov 13 '05 #11
Ed Morton wrote:


On 11/5/2003 3:42 PM, Alex wrote:
Ed Morton <mo************ ****@lucent.com > wrote:

<snip>
Not all OSs just use "\n" as the line terminator. Try adding "\n\r"
instead of
just "\n". This approach still fails if "fgets()" doesn't read to the end
of the line...

ITYM "\r\n". Also, I think that you're wrong.


Could be,


Trust me. He's right, you're wrong. Sorry, but there it is.

Whatever the platform's idea of newline is, a text file created in that
platform's native format, if opened in text mode in a C program, will
appear to have '\n' newlines, no matter what magic the runtime library must
do in order to achieve that.

(This doesn't mean that a Windows text file, opened on Linux, will magically
lose its '\r' characters. It won't.)

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #12


On 11/5/2003 4:36 PM, Richard Heathfield wrote:
Ed Morton wrote:


On 11/5/2003 3:42 PM, Alex wrote:
Ed Morton <mo************ ****@lucent.com > wrote:


<snip>
Not all OSs just use "\n" as the line terminator. Try adding "\n\r"
instead of
just "\n". This approach still fails if "fgets()" doesn't read to the end
of the line...
ITYM "\r\n". Also, I think that you're wrong.


Could be,

Trust me. He's right, you're wrong. Sorry, but there it is.


What? How dare you? That's it - you're killfiled for 90 days.

That is the appropriate response to being politely corrected these days, isn't
it ;-).

Thanks,

Ed.

Nov 13 '05 #13
William Payne wrote:

Hello, I need to write a program that opens a text file and scans
the entire file for a specific line and when that line is found,
a particular word on that line is to be replaced. The new word is
given as an argument to the program. I wrote a small test program
that doesn't work because strcmp() fails to find a matching line.
Here's the code:

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv)
{
FILE* in_file = NULL;
FILE* out_file = NULL;
char* temporary_file_ name = NULL;
char line[128];

if(argc < 2)
style note: if is not a function, follow it with a blank.
{
fprintf(stderr, "You must supply a word.\n");
return 1;
Undefined behaviour. #include <stdlib.h> and use return
EXIT_FAILURE.
}
in_file = fopen("test.txt ", "r");
if(in_file == NULL)
{
fprintf(stderr, "Error opening test.txt\n");
return 1;
same thing here.
}
temporary_file_ name = tmpnam(NULL);
out_file = fopen(temporary _file_name, "w");

while(fgets(lin e, sizeof(line), in_file))
{
printf("Line read: %s\n", line);
if(strcmp(line, "set imap_user=root" ) == 0)
Can never succeed. If the input line was less than 127 chars it
had at least a terminal '\n' in it. If longer the first 127 chars
wouldn't match your comparee.
{
printf("Replaci ng.\n");
strcpy(line, "set imap_user=");
strcat(line, argv[1]);
and even if it did compare, the result would have no final '\n'.
}

fputs(line, out_file);
}
fclose(in_file) ;
fflush(out_file );
fclose(out_file );

remove("test.tx t");
rename(temporar y_file_name, "test.txt") ;

return 0;
}
.... snip ...
Why doesn't it work?


Because you were very very sloppy (you asked). See above. Read
the descriptions of all the standard functions you are using. You
get points for proper declaration of main, returning a value, and
testing fopen results. You lose points for failure to check the
success of fclose, fflush, remove, and rename, failure of which
could result in permanent loss of data.

You might be advised to use a more forgiving input function. You
are welcome to ggets, available at:

<http://cbfalconer.home .att.net/download/ggets.zip>

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 13 '05 #14
Ed Morton <mo************ ****@lucent.com > wrote:

On 11/5/2003 3:42 PM, Alex wrote:
Ed Morton <mo************ ****@lucent.com > wrote: <snip>
Not all OSs just use "\n" as the line terminator. Try adding "\n\r" instead of
just "\n". This approach still fails if "fgets()" doesn't read to the end of
the line...

ITYM "\r\n". Also, I think that you're wrong.

Could be, but just using "\n" doesn't work for him. I suppose there could just
be white-space at the end of the line. Either way...
In fact, I suggested truncating the newline precisely because
it makes spotting other input anomalies (i.e. white space) much
easier.
<snip>
At any rate, I think that it is far better to either truncate the
newline sequence, or use strncmp.
Truncating the newline sequence might be tough if it really isn't always "\n"
....but it is!
and you'd also want to truncate trailing white-space. I'd go with "strncmp()"
plus "strlen()".


If you mean using the latter as an argument to the former, sure,
but how you get the length is not germane to my point.

Alex
Nov 13 '05 #15
Ed Morton <mo************ ****@lucent.com > wrote:

On 11/5/2003 3:25 PM, William Payne wrote:
<snip>
But strcmp() never returns 0 so no replacement is made. So then I tried
replacing the call to strcmp() with the following:
if(strstr(line, "set imap_user=root" ) != NULL)

and now it founds a match one the correct line and correctly replaces the
word. Very good, but it annoys me that I don't know why strcmp() doesn't
work.
See my previous response. This should work for you: while(fgets(lin e, sizeof(line), in_file))
{
printf("Line read: %s\n", line); if(strncmp(line , "set imap_user=root" , sizeof "set imap_user=root" - 1 ) =
= 0)
{


Yes, this should work. However, I would recommend that

a) The string should be a constant defined elsewhere so that
you do not have to adjust both strings in case you decide
to change the format.

b) Use strlen instead of sizeof and lose the "-1".

Design advice to the OP:

I am guessing that you are reading in options from a file.
Things like that are much better served by some sort of a table
form such as:

struct Option
{
char *p_option;
char *p_value;
}

Parse your input into an array or linked list of such structures
in a normalized fashion, discarding newlines and unnecessary
whitespace. Then you won't have to deal with input anomalies
elsewhere and using strcmp should suffice.

Alex
Nov 13 '05 #16


Alex wrote:
Ed Morton <mo************ ****@lucent.com > wrote: <snip> Yes, this should work. However, I would recommend that

a) The string should be a constant defined elsewhere so that
you do not have to adjust both strings in case you decide
to change the format.
That is what I suggested in the section you snipped.
b) Use strlen instead of sizeof and lose the "-1".


Probably not a big deal in this code, but just for information: Isn't
sizeof more efficient?

Ed.

Nov 13 '05 #17
On Wed, 5 Nov 2003 22:25:52 +0100, "William Payne"
Thanks for your reply, Mr Wahler. I tried this loop as you and others
suggested:

while(fgets(li ne, sizeof(line), in_file))
{
printf("Line read: %s", line);

if(strcmp(line, "set imap_user=root\ n") == 0)
{
printf("Replaci ng.\n");
strcpy(line, "set imap_user=");
strcat(line, argv[1]);
strcat(line, "\n");
}

fputs(line, out_file);
}

But strcmp() never returns 0 so no replacement is made.
You don't mention what compiler you're using, but the code works fine
when compiled with Turbo C 2.01.
So then I tried
replacing the call to strcmp() with the following:
if(strstr(line , "set imap_user=root" ) != NULL)

and now it founds a match one the correct line and correctly replaces the
word. Very good, but it annoys me that I don't know why strcmp() doesn't
work.

/ William Payne


Nov 13 '05 #18
Ed Morton <mo************ ****@lucent.com > wrote:

Alex wrote:
Ed Morton <mo************ ****@lucent.com > wrote: <snip>
Yes, this should work. However, I would recommend that

a) The string should be a constant defined elsewhere so that
you do not have to adjust both strings in case you decide
to change the format. That is what I suggested in the section you snipped.
My apologies, I missed it.
b) Use strlen instead of sizeof and lose the "-1".

Probably not a big deal in this code, but just for information: Isn't
sizeof more efficient?


Might be. However, as well all know, premature optimization is
the root of all evil. :-) With that in mind, 'strlen' is more
idiomatic for this case.

Alex
Nov 13 '05 #19

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

Similar topics

19
2950
by: rbt | last post by:
Here's the scenario: You have many hundred gigabytes of data... possible even a terabyte or two. Within this data, you have private, sensitive information (US social security numbers) about your company's clients. Your company has generated its own unique ID numbers to replace the social security numbers. Now, management would like the IT guys to go thru the old data and replace as many SSNs with the new ID numbers as possible. You...
1
5338
by: adam lital | last post by:
Hi, I have word document and i want to replace a specific text with a bookmark using code. Example: in the document i have the text and i want to replace this to a bookmark called ClientName. Thanks, Adam.
0
5739
by: Balakrsihna | last post by:
Hi All, Can anyone tell me how to replace an image in MS Word 2003 using c#.net. I am converting an html file to word doc and sending this as attachment using System.Web.Mail; the recipient could not see the image in attachment. I am using Inlinepicture.Addpicture but still not working
4
1529
by: Hemant | last post by:
Hi I want to replace a word using Regular Expression for that i am using below code strResult = System.Text.RegularExpressions.Regex.Replace(strInput, txtSearch.Text.ToString().Trim(), "<b>" + txtSearch.Text.ToString().Trim() + "</b>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); strInput = "This is a Test."
7
21060
by: gar | last post by:
Hi, I need to replace all the double quotes (") in a textbox with single quotes ('). I used this code text= Replace(text, """", "'" This works fine (for normal double quotes).The problem comes in when you copy a double quote from MS Word and paste it in the text box. What happens is the double quote becomes slanted (“) so my code above can't filter it. I tried to do this text= Replace(text, "““","'")
5
4794
by: Casey | last post by:
Hello, Can someone give me specific code to replace text on a page using server side javascript? I need to use server-side because I need the output to be recognized in the final HTML so that google can index it. Here is a specific example of what I want to do: <div id=SomeText> Here is some text. I went to the baseball game </div>
1
9087
by: Michael Yanowitz | last post by:
Hello: I am hoping someone knows if there is an easier way to do this or someone already implemented something that does this, rather than reinventing the wheel: I have been using the string.replace(from_string, to_string, len(string)) to replace names in a file with their IP address. For example, I have definitions file, that looks something like: 10.1.3.4 LANDING_GEAR 20.11.222.4 ALTIMETER_100
2
5109
by: Ola K | last post by:
Hi guys, I wrote a script that works *almost* perfectly, and this lack of perfection simply puzzles me. I simply cannot point the whys, so any help on it will be appreciated. I paste it all here, the string at the beginning explains what it does: '''A script for MS Word which does the following: 1) Assigns all Hebrew italic characters "Italic" character style. 2) Assigns all Hebrew bold characters "Bold" character style. 2) Assign all...
12
2095
by: implement | last post by:
Hi all! I try to code my own version of replace but it doesn't work. I hope somebody can help me out. It only replaces the first char!. Why I don't use the public string.replace function? Well I love implementing string functions :-). I coded another function for replacing chars in a word and this
3
3969
by: Hvid Hat | last post by:
Hi I want to highlight (make it bold) a word in some text I'm getting in XML format. My plan was to replace the word with a bold (or span) tag with the word within the tag. I've found the code below and it works fine as long as I'm not adding tags around the to parameter. Can anyone explain to me why it doesn't work with tags? And it needs to be XSLT 1.0. This works: X<xsl:value-of select="'little steak'"/>X This doesn't work:...
0
9997
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9845
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10870
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...
0
10499
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...
1
8047
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
6085
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4725
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
4306
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3323
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.