I am working on a code which opens a file (infile), copies it to an output file (outfile) and then asks the user for a string and searches for that string in the outfile and replaces every occurence of that string with & symbol.

Here's an example:

Contents of infile:

Mary had a little lamb
Whose fleece as white as snow

//the program will copy the file to an output file and then ask the user for a string that it will search in that file.

//For example, the user wants to look for all the occurrences of the 'as'.
//the program will search for all occurrences of 'as' and replace it with the '&' symbol:

Mary had a little lamb
Whose fleece & white & snow

So far, this is what I was able to do:

#include <stdio.h>
#include <string.h>

#define BUFF_SIZE 100

int main(int argc, char* argv[]) {

	char mystring[500];
	char out[1000];

	if (argc != 3) {
		fprintf(stderr, "Not enough parameters. Usage <progname> <infile> <outfile>\n");
		return -1;
	}

	FILE* inFile = fopen(argv[1], "rt");
	FILE* outFile = fopen(argv[2], "wt");
	if(!inFile) {
		fprintf(stderr, "File not found! Exiting.\n");
		return -1;
	}
	if(!outFile) {
		fprintf(stderr, "File can't be opened for writing.\n");
		return -1;
	}

	printf("Enter string to be searched:"); //asks the user to enter a string to be searched
	fgets(mystring, 500, stdin);

	if(strlen(mystring) < 2){ //checks if the user entered a string

		printf("You forgot to enter a string.");
		return -1;
		}

	while(!feof(inFile)){

	   fgets(out, 1000, inFile); //copies the text in the input File
	   fprintf(outFile, "%s", out); //prints the text from infile.txt to outfile.txt


		}

		
	return 0;
}

I was only able to recopy the contents of the input file. I'm actually stuck with the search and replace file. Can you guys give me some tips. I was thinking of using strstr function but I'm still a bit lost. Also, can you give some example for this one? Thanks

Member Avatar for iamthwee

Have a look at the code snippets section for c.

Beware of using feof to read in files as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.