I'm writing a C Program that changes all uppercase characters to lowercase from a certain file. The problem is, after storing all characters (processed) in a string, and trying to print all characters inside that file, they are appended to that file, and not overwritten. I'm using "r+" as a permission.
This is my code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define MAX 1024
int main(int argc, char **argv)
{
    if (argc != 2) {
        printf("Invalid number of arguments.\n");
        exit(1);
    }
    FILE *f = fopen(argv[1], "r+");
    if (f == NULL)
    {
        printf("Could not open specified file.\n");
        exit(2);
    }
    char buf[MAX];
    int len = 0;
    
    while(!feof(f))
    {
        int c = fgetc(f);
        if (c >= 'A' && c <= 'Z')
            c = tolower(c);
        if (c != EOF) {
            buf[len] = c;
            len++;
        }
    }
    for (int i = 0; buf[i] != '\0'; i++)
        fputc(buf[i], f);
    fclose(f);
    return 0;
}
Same problem with fputs(buf, f). Also even after appending, some "strange" characters appear at the end of the selected file.
What's the problem, exactly? How can I fix it? Thank you. Help would be appreciated.
 
    