如何替换C中文件的逐行文本?

我已经对此进行了一段时间的研究,却找不到任何可以帮助我解决特定问题的方法。

我有一个功能,需要在其中加密文件中的文本。我想要做的是从文本文件中读取一行并将其存储为字符串,对该字符串运行加密算法,然后将字符串的加密内容写回到该文件中。也就是说,我想用加密的行替换文件的当前行。

这是我到目前为止的内容:

int encrypt_file(char file_name[]) {
    FILE* file = fopen(file_name, "r+");

    if (file) {
        char line[300];
        while ((fgets(line, sizeof(line), file)) != NULL) {
            fseek(file, -(strlen(line)), SEEK_CUR);
            encrypt_string(line);
            if (fputs(line, file) == EOF) {
                printf("Error. Please try again.\n");
                fclose(file);
                return 1;
            }
        }
        fclose(file);
        return 0;
    } else {
        printf("Error. Ensure file exists and try again.\n");
        return 1;
    }
    fclose(file);
    return 0;
}

To explain my logic, I read the line from the file and then use fseek to move the pointer back by however many characters were read (it should now be at the beginning of the line). I then run the algorithm and then write the new string back into the file.

However, this code gives me an infinite loop. When I remove the fseek, it doesn't give me an infinite loop and it shows me that the algorithm has been correctly used on the string, but it shows the "Error. Please try again.\n" response and no changes have been made to the file itself.

任何帮助表示赞赏。