So I am trying to add text to the end of a line. Right now it adds it fine to the beginning but I can't figure out how to get it added to the end.
So the code here takes content from one file, and adds it to a temporary file, and than writes it back to the original file with the added text. Right now however its adding text to the beginning of the line, I need it at the end of each line.
Also I was wondering is there a way to just append text to the end of each line, without copying all contents to a temporary file, and just display the output to stdout?
int add_text_end(FILE *fileContents)
{
FILE *tmp = tmpfile();
char *p;
FILE *fp;
char line[LINESIZE];
if ((fileContents = fopen("fileContents.txt", "r")) == 0)
{
perror("fopen");
return 1;
}
/* Puts contents of file into temp file */
fp = fopen("fileContents.txt", "r");
while((p = fgets(line, LINESIZE, fp)) != NULL)
{
fputs(line, tmp);
}
fclose(fp);
rewind(tmp);
/* Reopen file to write to it */
fopen("fileContents.txt", "w");
while ((p = fgets(line, LINESIZE, tmp)) != NULL)
{
line[strlen(line)-1] = '\0'; /* Clears away new line*/
sprintf(line, "%s %s", line, "test");
fputs(line, fp);
}
fclose(fp);
fclose(tmp);
return 0;
}