Thread: Finding and replacing substrings

  1. #1
    Registered User
    Join Date
    Oct 2010

    Finding and replacing substrings

    Hi. Our C professor gave us the following problem:

    Develop a program that reads in the file /home/elliott/hw/hw2_input.txt. Your program should replace the word ”lamb” with ”sheep” and write the output back out to a file hw2_input.out. Your program should use the input file name to construct the output file name. So, if the input file name were test.txt, it would write out test.out.
    I wrote a code I think will work, but for some reason Putty and TeraTerm are both hating my computer tonight so I can't try it. I'll have access to the school computer's before it's due, but not for long so I really need to work out any big kinks before I go, because I won't have much time in the computer lab to do trial and error. Does my code make sense and should it likely work or am I using commands incorrectly?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    	FILE *fp1, *fp2;
    	char str[80];
    	char changeword[10] = sheep;
    	char *cp;
    	char OutfileName[32];
    	fp1 = fopen("/home/elliott/hw/hw2_input.txt", "r");
    	//create output file and name it
    	strcpy(OutfileName, fp1);
    	cp = memchr(OutfileName, '.', strlen(OutfileName)-1);
    	strcat(Outfilename, ".out", strlen(".out"));
    	fp2 = fopen(OutfileName, "w");
    	//go through each line and find the lambs
    	while (fgets(str, 80, fp)!=NULL){
    		if (strstr(str, "lamb")!=NULL) {
    			strcpy(lamb, changeword);
    		fprintf("%s\n", str);

  2. #2
    Registered User
    Join Date
    May 2010
    fopen/fclose not close! Pay attention to your compiler warning!
    strcpy(OutfileName, fp1); // copy file pointer to string?!

    cp = memchr(OutfileName, '.', strlen(OutfileName)-1); // why not use strchr?

    Better yet, go read some tutorial before trying out your assignment!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 10-31-2009, 04:10 AM
  2. Replacing a substring with another
    By Dan17 in forum C Programming
    Replies: 3
    Last Post: 09-14-2006, 10:37 AM
  3. Replacing and finding chars in a string
    By xshapirox in forum C++ Programming
    Replies: 5
    Last Post: 10-11-2004, 11:40 PM
  4. Question About Finding a Word and Replacing It
    By Zildjian in forum C Programming
    Replies: 3
    Last Post: 09-23-2003, 08:50 AM