The Problem was to find and replace a string in a C File.
I am new to C Files. I have tried the following code but I didnt get any output:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *f1,*f2;
char *src,*dest,*s1,ch,ch1,ch2,ch3;
int i;
f1=fopen("input.txt","rw");
f2=fopen("dummy.txt","rw");
src="mor";
dest="even";
while(ch!=EOF)
{
ch=fgetc(f1);
if(ch==src[0]) //Finding 1st char of src
{
fgets(s1,strlen(src),f1);
if(strcmp(src+1,s1)==0) //Finding occurance of "src" in file
{
fseek(f1,strlen(src)-1,SEEK_CUR);
while(ch1!=EOF) //Copying remaining data into another file
{
ch1=fgetc(f1);
fputc(ch1,f2);
}
fseek(f1,-strlen(src),SEEK_CUR);
for(i=0;i<strlen(dest);i++) //replacing "src" with "dest"
{
ch2=dest[i];
fputc(ch2,f1);
}
fclose(f1);
f1=fopen("input.txt","a");
while(ch3!=EOF) //Appending previosly copied data into 1st file
{
ch3=fgetc(f2);
fputc(ch3,f1);
}
}
}
}
fclose(f1);
fclose(f2);
}
The Contents of input.txt is “morning”.
Kindly point the ERROR in the logic and also give an efficient code for the same.
Thanks in Advance.
Reading files in C is usually a bit messy. The first problem that I see is the way ch is used in the main loop. The first time
is executed, ch is uninitialized, and if it happens to hold
EOF, the main loop will not execute at all. I usually use the following structure for reading from files:In addition, you may need to read up on file pointer concept. For example, after reading the remainder of
src, youfseek()forward, and skip some more characters before you copy data to f2. Essentially, you readm, reador(withfgets()– and into an unallocated buffers1that would go ka-boom on you some time in the near future), skip 2 more characters (now your pointer is at last n of “morning”), copy “ng” intof2, try to write EOF to f2 in this loop (hence the above pattern for reading untilEOF), seek two characters back (which may fail once you reachEOF, my C file functions are a bit rusty these days), write “even” to f1 (which should, if I am wrong about seek afterEOF, set input file to “mornieven”, and not change it if I am correct). In summary, I don’t think the code does what you intend it to do.I would recommend building up your function. Each one of the following can be written as a program that you should test and finish before going to next step:
src, and print the rest of inputsrcwithdestin first file, and ignore the rest (since you open input file with ‘rw’, this will truncate the rest of input). You may need to do an fseek() to clear the EOF status. Also look atftell()to record a position that you can jump back to usingfseek()srcwithdest(no need to close f1 here. But it is better to open f2 as write, close after copy from first file, and reopen as read to perform the copy back to f1).In addition, when you need a buffer (such as s1), just use a large enough array for now, but look into
malloc()andfree()functions to perform dynamic memory allocations for situations like these.