I'm trying to make a program that adds the string I want in the position I want in a file. When running the program it must be called like this: ./addString file_name position text
for example if I have a file that contains 123456789 and I add "hello" in position 3 the new file's content is 123hello456789 (position starts counting from 0). The problem comes when I try to add the new string in positions 0 and 9. It adds it correctly but at the end it also adds an extra string like ^G or ^YĆ6 and I don't know why.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
main (int argc, char * argv[]){
if(argc == 4){
FILE *fd;
long size, rest;
char c;
fd = fopen(argv[1], "r+");
fseek(fd, 0, SEEK_END);
size = ftell(fd)-1 ;
rest = size - atoi(argv[2]);
char buffer[rest];
fseek(fd, atoi(argv[2]), SEEK_SET);
int i = 0;
while(i < rest){
c=fgetc(fd);
buffer[i] = c;
i++;
}
fseek(fd, atoi(argv[2]), SEEK_SET);
fprintf(fd, "%s", argv[3]);
fprintf(fd, "%s", buffer);
fclose( fd );
}
}