I'm having a problem with updating my C code on VS Code(version 1.77.0) and/or Code Runner extension for C language. The issue is that I have to run or recompile the code twice to get it up-to-date after modifying anything. The program is to append a keyboard input to a textfile. For example when I run the program it asks for the user's name then appends it to the output file. When I modify the fprintf function to add a newline after the name it adds the newline after I run the code twice.
#include <stdio.h>
int main()
{
FILE *fPointer;
fPointer = fopen("output.txt", "a");
char name[30];
printf("Please enter your name: ");
scanf("%s", &name);
fprintf(fPointer, "%s", name);
fclose(fPointer);
return 0;
}
I modified the fprintf(fPointer, "%s", name);
to fprintf(fPointer, "%s\n", name);
to get the user inputs in different lines in the output file.
I run the version of the program that doesn't add the newline character and input "myname" and get:
myname
on the output file. Then I modify the code to add a newline character when printing the user input to the output file.
#include <stdio.h>
int main()
{
FILE *fPointer;
fPointer = fopen("output.txt", "a");
char name[30];
printf("Please enter your name: ");
scanf("%s", &name);
fprintf(fPointer, "%s\n", name);
fclose(fPointer);
return 0;
}
After I run the new version for the first time and input "name2" I get
mynamename2
It should've been
myname
name2
Even though I change nothing and run the program again and input "name3",I get
mynamename2
name3
I tried playing with the autosave setting both for VS Code and the Code Runner extension, but those didn't really change anything. Manually saving is not working as well.
Your first run of the first version of the program doesn't print a trailing newline. You open the file again to append to it with your modified file, and your modified file puts the newline character at the end. It's no wonder that when it appends to the previous content, it doesn't put a newline between the original content and the new content, and instead puts a newline after the new content. That's why when you open the file the third time to append to it, it starts on the newline that got added in the second run. And then it adds a newline character after the third run's new content.
Everything is behaving exactly as it should.
A lesson in data formats and migrations: when you change your data format, in addition to changing the way your programs writes/updates the data, you need to update the existing data to match the new format as well (your "new format" is ending ("delimiting") each piece of data with a newline character)