Finding and replacing substrings

This is a discussion on Finding and replacing substrings within the C Programming forums, part of the General Programming Boards category; 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 ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    10

    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?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    main(){
    
    	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);
    	}
    	close(fp1);
    	close(fp2);
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    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, 05:10 AM
  2. Replacing a substring with another
    By Dan17 in forum C Programming
    Replies: 3
    Last Post: 09-14-2006, 11:37 AM
  3. Replacing and finding chars in a string
    By xshapirox in forum C++ Programming
    Replies: 5
    Last Post: 10-12-2004, 12:40 AM
  4. Question About Finding a Word and Replacing It
    By Zildjian in forum C Programming
    Replies: 3
    Last Post: 09-23-2003, 09:50 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21