473,748 Members | 11,145 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 #1
18 21899
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.
That's because fgets doesn't strip the newline (assuming it finds one in the
available space).
while(fgets(lin e, sizeof(line), in_file))
{
printf("Line read: %s\n", line);

if(strcmp(line, "set imap_user=root" ) == 0)


I suggest you replace this line with:

if(strcmp(line, "set imap_user=root\ n") == 0)

--
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 #2


On 11/5/2003 2:58 PM, 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:
<snip> while(fgets(lin e, sizeof(line), in_file))
{
printf("Line read: %s\n", line);

if(strcmp(line, "set imap_user=root" ) == 0)


fgets() copies the newline char to the end of the string, so "line" ends in a
newline whereas "set imap_user=root" doesn't.

Ed.

Nov 13 '05 #3

"William Payne" <mi************ **@student.liu. se> wrote in message
news:bo******** **@news.island. liu.se...
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)
Change the above line to:

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");

/* you should also provide protection against 'strcat()'
overflowing the array 'line' */
}

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?


'fgets()' stores the newline (if any) that it reads.

My above changes aren't foolproof, i.e. if the line read
has 'trailing spaces' before the newline, or if 'fgets()'
doesn't read a newline, then it won't work.

-Mike
Nov 13 '05 #4

"Richard Heathfield" <do******@addre ss.co.uk.invali d> wrote in message
news:bo******** **@titan.btinte rnet.com...
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.
That's because fgets doesn't strip the newline (assuming it finds one in

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

if(strcmp(line, "set imap_user=root" ) == 0)


I suggest you replace this line with:

if(strcmp(line, "set imap_user=root\ n") == 0)

--
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


Thanks for the quick reply, Mr Heathfield. It appears that you are right
about fgets() not stripping the newline because I got an empty line between
the printf()-statements in the while()-loop. So I wrote strcmp() as you
suggested, but it still fails to match the string. =( Any ideas?

/ William Payne
Nov 13 '05 #5

"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:SI******** ********@newsre ad4.news.pas.ea rthlink.net...

"William Payne" <mi************ **@student.liu. se> wrote in message
news:bo******** **@news.island. liu.se...
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)


Change the above line to:

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");

/* you should also provide protection against 'strcat()'
overflowing the array 'line' */
}

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?


'fgets()' stores the newline (if any) that it reads.

My above changes aren't foolproof, i.e. if the line read
has 'trailing spaces' before the newline, or if 'fgets()'
doesn't read a newline, then it won't work.

-Mike


Thanks for your reply, Mr Wahler. I tried this loop as you and others
suggested:

while(fgets(lin e, 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. 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 #6


On 11/5/2003 3:14 PM, William Payne wrote:
"Richard Heathfield" <do******@addre ss.co.uk.invali d> wrote in message
news:bo******** **@titan.btinte rnet.com... <snip>
I suggest you replace this line with:

if(strcmp(line, "set imap_user=root\ n") == 0)

<snip> Thanks for the quick reply, Mr Heathfield. It appears that you are right
about fgets() not stripping the newline because I got an empty line between
the printf()-statements in the while()-loop. So I wrote strcmp() as you
suggested, but it still fails to match the string. =( Any ideas?
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...

Ed.
/ William Payne


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

On 11/5/2003 3:14 PM, William Payne wrote:
"Richard Heathfield" <do******@addre ss.co.uk.invali d> wrote in message
news:bo******** **@titan.btinte rnet.com... <snip>
I suggest you replace this line with:

if(strcmp(line, "set imap_user=root\ n") == 0)

<snip>
Thanks for the quick reply, Mr Heathfield. It appears that you are right
about fgets() not stripping the newline because I got an empty line between
the printf()-statements in the while()-loop. So I wrote strcmp() as you
suggested, but it still fails to match the string. =( Any ideas?

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.

IIRC, when a file is opened as a text stream, '\n' is the newline
character, regardless of the system particulars. When dealing with
binary streams, this does become and issue, but this is not the case
here.

At any rate, I think that it is far better to either truncate the
newline sequence, or use strncmp.

Alex
Nov 13 '05 #8


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.
/ William Payne


Nov 13 '05 #9


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...

<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"
and you'd also want to truncate trailing white-space. I'd go with "strncmp()"
plus "strlen()".

Ed.
Alex


Nov 13 '05 #10

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

Similar topics

19
2934
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
5329
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
5719
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
1522
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
21003
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
4784
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
9070
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
5097
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
2084
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
3963
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:...
1
9319
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
9243
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
6795
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
6073
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();...
0
4599
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
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
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
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
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.