1、逐字符读取并打印
最简单的方法,适用于打印整个文件内容。
#include <stdio.h> int main() { FILE *file = fopen("test.txt", "r"); if (file) { int c; while ((c = getc(file)) != EOF) putchar(c); fclose(file); } else { perror("Failed to open file"); } return 0; }
2、按行读取并打印
如希望逐行读取文件内容,可以使用 fgets
。
#include <stdio.h> int main() { FILE *file = fopen("test.txt", "r"); if (file) { char buffer[1024]; while (fgets(buffer, sizeof(buffer), file)) printf("%s", buffer); fclose(file); } else { perror("Failed to open file"); } return 0; }
3、读取整个文件到内存并打印
如需要将整个文件内容读取到一个字符串中,可以使用以下方法。
#include <stdio.h> #include <stdlib.h> char* read_file(const char *filename) { FILE *file = fopen(filename, "r"); if (!file) return NULL; fseek(file, 0, SEEK_END); long length = ftell(file); rewind(file); char *buffer = malloc(length + 1); if (!buffer) { fclose(file); return NULL; } fread(buffer, 1, length, file); buffer[length] = '\0'; fclose(file); return buffer; } int main() { char *content = read_file("test.txt"); if (content) { printf("%s", content); free(content); } else { perror("Failed to read file"); } return 0; }
4、按单词读取并打印
如希望逐个单词读取文件内容,可以使用 fscanf
。
#include <stdio.h> int main() { FILE *file = fopen("test.txt", "r"); if (file) { char word[100]; while (fscanf(file, "%99s", word) == 1) printf("%s\n", word); fclose(file); } else { perror("Failed to open file"); } return 0; }