thx again for your quick reply
the first one i understand now
but when i follow the second piece of code
i got this
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 seen_first = 0;
puts("Enter filename to search: ");
fgets(filename,sizeof(filename),stdin);
char *p = strchr( filename, '\n' );
if ( p != NULL )
*p = '\0';
puts("Enter tmpfile: ");
fgets(tmpname, sizeof(tmpname), stdin);
p = strchr( tmpname, '\n' );
if ( p != NULL )
*p = '\0';
puts("Enter string to search: ");
fgets(str_search,sizeof(str_search),stdin);
p = strchr( str_search, '\n' );
if ( p != NULL )
*p = '\0';
puts("Enter string to replace");
fgets(str_replace, sizeof(str_replace), stdin);
p = strchr( str_replace, '\n' );
if ( p != NULL )
*p = '\0';
if ((fp = fopen(filename, "r")) == NULL)
{
fprintf(stderr ,"Error opening filename");
exit(-1);
}
if ((tmpfp = fopen(tmpname, "w")) == NULL)
{
fprintf(stderr,"Error opening filename");
exit(-1);
}
while(fgets(buffer,BUFSIZE,fp) != NULL);
{
if(strstr(buffer, str_search) != NULL)
{
if (!seen_first)
{
fputs(buffer, tmpfp);
seen_first = 1;
}
else
{
fputs(str_replace, tmpfp);
}
}
else
{
fputs(buffer, tmpfp);
}
}
fclose(fp);
fclose(tmpfp);
/*rename(tmpname,filename);*/
return 0;
}
result
only the last line is in the file that
i specified as tmpfile
when i
replace
Code:
puts("Enter tmpfile: ");
fgets(tmpname, sizeof(tmpname), stdin);
p = strchr( tmpname, '\n' );
if ( p != NULL )
*p = '\0'
with
tmpname(tmpname);
i get the following messages
tmp/ccDoSU1B.o: In function `main':
/tmp/ccDoSU1B.o(.text+0x179): the use of `tmpnam' is dangerous, better use `mkstemp'
thx again for your help