阅读量:6
在C语言中,可以使用标准库函数fscanf或fgets来读取文件中的字符串。
- 使用
fscanf函数:
#include
int 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函数:
#include
int 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)指定了读取的最大字符数,避免了缓冲区溢出的问题。
以上就是关于“c语言如何读取文件中的字符串”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm