在C语言中,可以使用标准库函数fscanf
或fgets
来读取文件中的字符串。
- 使用
fscanf
函数:
#includeint main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("无法打开文件\n"); return 1; } char str[100]; while (fscanf(file, "%s", str) != EOF) { printf("%s\n", str); } fclose(file); return 0; }
上述代码打开名为example.txt
的文件并从中读取字符串,每次读取一个字符串并打印出来,直到文件末尾。
- 使用
fgets
函数:
#includeint main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("无法打开文件\n"); return 1; } char str[100]; while (fgets(str, sizeof(str), file) != NULL) { printf("%s", str); } fclose(file); return 0; }
上述代码使用fgets
函数从文件中逐行读取字符串并打印出来,直到文件末尾。sizeof(str)
指定了读取的最大字符数,避免了缓冲区溢出的问题。