replacing string in file except the first
hi everyone
it my first post here
my problem is i want ot replace a string of text
in a file the files are one a one word/one line
bases
i have come this far but i don't seem to get
strstr() to work
would it also be possible to a sort of temp file
in place of asking for the tempfile
i there a way that i can avoid gets()
cause my compiler says that is dangerous
but when i use fgets or scanf i got no result
this my fisrt program ever so be nice
if it looks crappy
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 255
int main (void)
{
char filename[BUFSIZE];
char tmpname[BUFSIZE];
char str_search[BUFSIZE];
char str_replace[BUFSIZE];
FILE *fp;
FILE *tmpfp;
char buffer[BUFSIZE];
int count = 0, count_lines = 0;
char *loc;
int first;
puts("Enter filename to search: ");
gets(filename);
puts("Enter tmpfilename");
gets(tmpname);
puts("Enter string to search: ");
gets(str_search);
puts("Enter string to replace");
gets(str_replace);
if ((fp = fopen(filename, "rb")) == NULL)
{
fprintf(stderr ,"Error opening filename");
exit(-1);
}
if ((tmpfp = fopen(tmpname, "wb")) == NULL)
{
fprintf(stderr,"Error opening filename");
exit(-1);
}
while(!feof(fp))
{
fgets(buffer,BUFSIZE,fp);
count++;
}
count_lines = count;
rewind(fp);
count = 0;
while(!feof(fp))
{
fgets(buffer,BUFSIZE,fp);
count++;
if((strstr(buffer, str_search) != NULL))
{
first = count;
break;
}
}
rewind(fp);
for(count = 0; count < count_lines-1; count++)
{
fgets(buffer,BUFSIZE,fp);
loc = strstr(buffer, str_replace);
printf("%d\n" , loc-buffer);
if (loc != NULL && count != count_lines)
{
fputs(str_replace, tmpfp);
}
else
{
fputs(buffer, tmpfp);
}
}
fclose(fp);
fclose(tmpfp);
/*rename(tmpname,filename);*/
return 0;
}
an example of the test file
we
came
here
we
came
here
replace we with they or whatever
thx in advance