Add data to end of a line in file C (without using second file)

Viewed 56

That's the file I have:

Line 1
Line 2
Line 3

And I want to add some character/string at the end of each line. I did some research but haven't found any solution that's not use an additional file. Here is what I came up with:

char c;
FILE *fp1 = fopen("Test.txt", "r+");
while ((c = fgetc(fp1)) != EOF){
    if (c == '\n'){
        fseek(fp1, -2, SEEK_CUR); // the '\n' is 2 bytes
        fputs("X\n", fp1);
        fseek(fp1, 1, SEEK_CUR);
    }
}

It appends the string but deletes the first n characters of the newline (n - is a length of the string that I want to input). Output:

Line 1 X
ine 2 X
ine 3 X

1 Answers

What program does sounds logical: you have a sequence of characters. Newline is just another caracter with its own code. So if you want to paste some text in the middle of that sequence - you need to move everything to the right as far as many characters you want to paste. In your case it's 1 character, I suppose. So you'd need to read everything after your newline, paste "X" and then newline and everything after it.

Related