Replace word in text file

W

William Payne

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(line, sizeof(line), in_file))
{
printf("Line read: %s\n", line);

if(strcmp(line, "set imap_user=root") == 0)
{
printf("Replacing.\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.txt");
rename(temporary_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
 
R

Richard Heathfield

William said:
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(line, 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)
 
E

Ed Morton

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:

while(fgets(line, 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.
 
M

Mike Wahler

William Payne said:
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(line, 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("Replacing.\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.txt");
rename(temporary_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
 
W

William Payne

Richard Heathfield said:
That's because fgets doesn't strip the newline (assuming it finds one in the
available space).


I suggest you replace this line with:

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

--
Richard Heathfield : (e-mail address 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

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
 
E

Ed Morton

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

William Payne

Mike Wahler said:
William Payne said:
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(line, 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("Replacing.\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.txt");
rename(temporary_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(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. 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
 
A

Alex

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
 
E

Ed Morton

On 11/5/2003 3:25 PM, William Payne wrote:
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.
 
E

Ed Morton

Ed Morton <[email protected]> wrote:


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

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

Jens.Toerring

On 11/5/2003 3:25 PM, William Payne wrote:
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")

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
--
_ _____ _____
| ||_ _||_ _| (e-mail address removed)-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring
 
R

Richard Heathfield

Ed said:
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.)
 
E

Ed Morton

Ed Morton wrote:




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

CBFalconer

William said:
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;

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

Alex

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

Alex

On 11/5/2003 3:25 PM, William Payne wrote:
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
 
E

Ed Morton

Alex said:
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.
 
A

Andy

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

Alex

That is what I suggested in the section you snipped.

My apologies, I missed it.
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top