I'm trying to write a program that will open an existing file supplied by the command line argument and then replace words with "We" or "we" by "I" and "a" or "A" by "The". When I run the program it reads the file, changes the word but re writes it on a new line with only the replaced words not the whole sentence. Would anyone be able to help me?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFERSIZE 4096
main(int ac, char *av[])
{
int in_fd, n_chars;
char buf[BUFFERSIZE];
char x;
/* check args */
if ( ac != 2 ){
fprintf( stderr, "usage: %s source destination\n", *av);
exit(1);
}
/* open files */
if ( (in_fd=open(av[1], O_RDWR)) == -1 )
printf("Cannot open ", av[1]);
while ( (n_chars = read(in_fd , buf, BUFFERSIZE)) > 0 ){
for (x=0; x<n_chars; x++)
{
if (buf[x] == 'W') if (buf[x+1] == 'e') if (buf[x+2]=' ')
{
lseek(in_fd, 0, SEEK_CUR);
write(in_fd, "I", strlen("I"));
}
if (buf[x] == 'w') if (buf[x+1] == 'e') if (buf[x+2]=' ')
{
lseek(in_fd, 0, SEEK_CUR);
write(in_fd, "I", strlen("I"));
}
if (buf[x] == 'A') if (buf[x+1] == ' ')
{
lseek(in_fd, 0, SEEK_CUR);
write(in_fd, "The", strlen("The"));
}
if (buf[x] == 'a') if (buf[x+2] == ' ')
{
lseek(in_fd, 0, SEEK_CUR);
write(in_fd, "the", strlen("the"));
}
write( in_fd, &buf[x], 1 );
}
}
if ( n_chars == -1 )
printf("Read error from ", av[1]);
if ( close(in_fd) == -1)
printf("Error closing files","");
}