I am trying to write a linux command called replace which will replace characters in a file. I hope to call it like so:
$./replace I XY test.txt
In this example, test.txt
contains the words "THIS IS A TEST FILE"
How can I replace the character 'I'
with "XY"
. I have tried to use a buffer such as the code given below, but due to the fact that the buffer and argv are declared differently, it produces an error. Furthermore, 'I'
is stored in one array element, whereas "XY"
requires two. Does there exist a workaround for this?
Consider the text.txt
example:
[T][H][I][S][ ][I][S][ ][A][ ][T][E][S][T][ ][F][I][L][E]
In this example, the third index (which contains 'I'
) must be replaced with "XY"
Here's my code, which has the issue described above:
#define BUFFERSIZE 4096
/*replace i xy data.txt */
int main(int ac, char *av[])
{
int in_fd, out_fd, n_chars, BufElement,j;
char buf[BUFFERSIZE];
in_fd=open(av[3], O_RDWR);
/*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++)
{
if (buf[BufElement] == av[1][j])
buf[BufElement] = av[2]; /*ERROR*/
}/*for*/
}/*for*/
}/*while*/
}/*main*/