温馨提示×

如何使用Fopen以追加模式写入

小樊
90
2024-06-17 18:15:00
栏目: 编程语言

要使用fopen函数以追加模式写入文件,需要指定第二个参数为"a"。这将打开文件以追加模式,并将文件指针移动到文件末尾,以便在文件的末尾添加新的内容。

以下是一个示例代码,演示如何使用fopen以追加模式写入文件:

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "a");
    
    if (file) {
        fprintf(file, "This is a new line that will be added to the file.\n");
        fclose(file);
        printf("Content has been successfully added to the file.\n");
    } else {
        printf("Failed to open the file.\n");
    }

    return 0;
}

在这个例子中,fopen函数以追加模式打开名为example.txt的文件。然后,使用fprintf函数将新的内容写入到文件中,并最后使用fclose函数关闭文件。

请注意,如果文件不存在,fopen函数将创建一个新的文件。如果文件已经存在,fopen将会将文件指针移动到文件末尾,以便在文件的末尾添加新的内容。

0