C 语言实例 - 从文件中读取一行
C 语言教程
· 2019-02-21 11:27:01
从文件中读取一行。
文件 codercto.txt 内容:
$ cat codercto.txt codercto.com google.com
实例
#include <stdio.h>
#include <stdlib.h> // exit() 函数
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("codercto.txt", "r")) == NULL)
{
printf("Error! opening file");
// 文件指针返回 NULL 则退出
exit(1);
}
// 读取文本,直到碰到新的一行开始
fscanf(fptr,"%[^\n]", c);
printf("读取内容:\n%s", c);
fclose(fptr);
return 0;
}
输出结果为:
读取内容: codercto.com
点击查看所有 C 语言教程 文章: https://codercto.com/courses/l/17.html