在C语言中,可以使用stdio.h头文件中的函数来读写txt文件。
打开文件:可以使用fopen函数来打开一个txt文件。该函数的原型为:FILE *fopen(const char *filename, const char *mode)。
读取文件:可以使用fgets函数从打开的文件中读取内容。该函数的原型为:char *fgets(char *str, int n, FILE *stream)。
FILE *file = fopen("example.txt", "r");if (file == NULL) { printf("Failed to open file.\n"); return 1;}char buffer[100];while (fgets(buffer, sizeof(buffer), file) != NULL) { printf("%s", buffer);}fclose(file);写入文件:可以使用fprintf函数将内容写入文件。该函数的原型为:int fprintf(FILE *stream, const char *format, ...)。stream是文件指针,指向已经打开的文件。format是要写入的格式化字符串,可以使用类似printf函数的格式占位符。FILE *file = fopen("example.txt", "w");if (file == NULL) { printf("Failed to open file.\n"); return 1;}fprintf(file, "Hello, World!\n");fprintf(file, "This is a test file.\n");fclose(file);以上代码演示了如何读取和写入txt文件。需要注意的是,在使用完文件后,需要使用fclose函数关闭文件。

