logic error? replace characters in a file
user types $./replace i xy data.txt
data.txt contains the words "this is a test file, test file only". Therefore, all i's will be replaced with xy, i.e. thxys xys a test fxyle, test fxyle only
I think I am quite close. However, instead of replacing i with xy, my code just replaces i with x. I think the error is at line 38 strcpy.
However, is the logic correct from line 30 to 40? I am trying to say....
For each element in the first buffer(buf)
copy buf element into another buffer (temp) one character at a time
if buf element == 'i'
copy 'xy' to 'i'
Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 4096
/*replace i xy data.txt */
int main(int ac, char *av[])
{
int in_fd, out_fd, n_chars, BufElement,j,x;
ssize_t nread,nwrite;
off_t newpos;
char buf[BUFFERSIZE],temp[300];
/*Open file containing original data*/
if ( (in_fd=open(av[3], O_RDWR)) == -1 )
{
printf("Cannot open %s\n", av[3]);
exit(1);
}
/*Read characters from file to buffer*/
while ( (nread = read(in_fd , buf, BUFFERSIZE)) > 0 )
{
for (BufElement=0;BufElement < nread;BufElement++)
{
for (j=0; j < strlen(av[1]); j++)
{
temp[BufElement] = buf[BufElement];
if (buf[BufElement] == av[1][j])
strncpy(temp+BufElement,av[2],strlen(av[2])); /*ERROR*/
}
}
}
printf("%s\n",buf);
printf("%s\n",temp);
newpos = lseek(in_fd, 0, SEEK_SET);
nwrite = write(in_fd,temp,36);
close(in_fd);
}
}