Hi! I'm new to C and I'm having some problems in my program. It opens a .txt file then copies this to another .txt file but replaces a certain word with another word. It uses command line arguments. Example:
//inside text.txt
love is patient
love is kind
...
./change love MONEY text.txt text_new.txt
Output:
//generates a .txt file <text_new.txt>. inside is
MONEY is patient
MONEY is kind
...
I'm having problems replacing the words. We're asked to use strtok(). Here is my code
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
FILE *oldfile;
FILE *newfile;
unsigned int i=0;
char c;
char str[1000]; //just a random number of elements
char *result=NULL;
//CHECK NUMBER OF ARGUMENTS
if (argc<5){
printf("Error: Not enough input parameters\nUsage: ./exer09_02 <oldword> <newword> <infile> <newfile>\n");
return 1;
}
//OPEN FILE
oldfile = fopen(argv[3],"r");
//CHECK IF FOPEN IS SUCCESSFUL
if (oldfile==NULL){
printf("ERROR: %s does not exist\n",argv[3]);
return 1;
}
//CREATE NEW FILE
newfile = fopen(argv[4], "w+");
if (newfile!=NULL)
printf("New file <%s> generated!\n",argv[4]);
//COPY CONTENTS OF OLDFILE TO A STRING FOR PARSING
c = fgetc(oldfile);
while(c!=EOF){
str[i] = c;
i++;
c = fgetc(oldfile);
}
str[i] = '\0';
//FIND AND REPLACE A WORD WITH ANOTHER WORD
result = strtok(str," ");
while(result!=NULL){
if (strncmp(result,argv[1],strlen(argv[1])-1)==0){
strncpy(result,argv[2],strlen(argv[2]));
fprintf(newfile,"%s ",result);
}
result = strtok(NULL," ");
}
fclose(oldfile);
fclose(newfile);
return 0;
}
Instead of having a correct result, what happens in my code is it generates a text_new.txt file containing:
MONEYis patient
love is kind
...
Only "love" in the first line gets replaced, and if there are letters exceeding four, it eats away at the characters after. I can't seem to find where I got it wrong. Hope someone helps me. Thanks in advance!