Hello,
I'm currently writing a program for my C course at University where I have to read in lines of input from stdin, replace a specified word with another word (from command line arguments), and ouput to stdout. I have that part working with the following code:
Code:
#include <stdio.h>
#include <string.h>
main(int argc, char *argv[]) {
char buf[BUFSIZ];
char *tok;
// read lines from stdin
while ( fgets(buf, BUFSIZ, stdin) ) {
// tokenize line using strtok
for (tok = strtok(buf," "); tok != NULL; tok = strtok(NULL," ")) {
if (strcmp(tok,argv[1]) == 0) printf("%s ",tok = argv[2]);
else if (strchr(tok,'\n')) printf("%s",tok);
else printf("%s ",tok);
}
}
}
What I also have to do, though, is if the word I'm looking for has the newline character in it, I have to output a message to stderr. What I want to do is make a new string that has the newline character concatenated onto argv[1] as follows:
Code:
#include <stdio.h>
#include <string.h>
main(int argc, char *argv[]) {
char buf[BUFSIZ];
char *tok;
char *error = strcat(argv[1],"\n");
// read lines from stdin
while ( fgets(buf, BUFSIZ, stdin) ) {
// tokenize line using strtok
for (tok = strtok(buf," "); tok != NULL; tok = strtok(NULL," ")) {
if (strcmp(tok,error) == 0) {
fprintf(stderr, "Invalid input.\n");
exit(1);
}
if (strcmp(tok,argv[1]) == 0) printf("%s ",tok = argv[2]);
else if (strchr(tok,'\n')) printf("%s",tok);
else printf("%s ",tok);
}
}
}
After I compile and run this code, argv[1] does not get replaced by argv[2]. I think it's because when I create the error string, I change what argv[1] is. Is there something to stop this from happening? I'm thinking that there must be a way to make a copy of argv[1], but I don't know how to do this. Any help would be greatly appreciated.