Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Replace word in text file

Reply
Thread Tools

Replace word in text file

 
 
Jens.Toerring@physik.fu-berlin.de
Guest
Posts: n/a
 
      11-05-2003
Ed Morton <(E-Mail Removed)> 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(line, 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=rootcrop")


> 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
--
_ _____ _____
| ||_ _||_ _| http://www.velocityreviews.com/forums/(E-Mail Removed)-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring
 
Reply With Quote
 
 
 
 
Richard Heathfield
Guest
Posts: n/a
 
      11-05-2003
Ed Morton wrote:

>
>
> On 11/5/2003 3:42 PM, Alex wrote:
>> Ed Morton <(E-Mail Removed)> 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 : http://www.velocityreviews.com/forums/(E-Mail Removed)
"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
 
Reply With Quote
 
 
 
 
Ed Morton
Guest
Posts: n/a
 
      11-05-2003


On 11/5/2003 4:36 PM, Richard Heathfield wrote:
> Ed Morton wrote:
>
>
>>
>>On 11/5/2003 3:42 PM, Alex wrote:
>>
>>>Ed Morton <(E-Mail Removed)> 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.

 
Reply With Quote
 
CBFalconer
Guest
Posts: n/a
 
      11-05-2003
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(line, 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("Replacing.\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.txt");
> rename(temporary_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 ((E-Mail Removed)) ((E-Mail Removed))
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

 
Reply With Quote
 
Alex
Guest
Posts: n/a
 
      11-05-2003
Ed Morton <(E-Mail Removed)> wrote:


> On 11/5/2003 3:42 PM, Alex wrote:
>> Ed Morton <(E-Mail Removed)> 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
 
Reply With Quote
 
Alex
Guest
Posts: n/a
 
      11-05-2003
Ed Morton <(E-Mail Removed)> 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(line, 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
 
Reply With Quote
 
Ed Morton
Guest
Posts: n/a
 
      11-06-2003


Alex wrote:
> Ed Morton <(E-Mail Removed)> 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.

 
Reply With Quote
 
Andy
Guest
Posts: n/a
 
      11-06-2003
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(line, sizeof(line), in_file))
> {
> printf("Line read: %s", line);
>
> if(strcmp(line, "set imap_user=root\n") == 0)
> {
> printf("Replacing.\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
>


 
Reply With Quote
 
Alex
Guest
Posts: n/a
 
      11-07-2003
Ed Morton <(E-Mail Removed)> wrote:


> Alex wrote:
>> Ed Morton <(E-Mail Removed)> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: OT: Text editors (was Re: Search and replace text in XML file?) Tim Chase Python 10 08-31-2012 03:56 AM
OT: Text editors (was Re: Search and replace text in XML file?) Chris Angelico Python 9 07-29-2012 05:55 PM
How to extract part of the text (htm) file after start word until end word? Perl Misc 4 05-12-2006 06:51 PM
replace text in IFRAME using innerHTML.replace(...) possible? mscir Javascript 0 10-11-2005 11:21 PM
Word file not opening from Adm -My recent docs but opening from file menu of Word Thaqalain Computer Support 0 06-30-2005 02:20 AM



Advertisments