C 语言实例 - 从文件中读取一行
从文件中读取一行。
文件 runoob.txt 内容:
$ cat runoob.txt runoob.com google.com
实例
#include <stdio.h>
#include <stdlib.h> // exit() 函数
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("runoob.txt", "r")) == NULL)
{
printf("Error! opening file");
// 文件指针返回 NULL 则退出
exit(1);
}
// 读取文本,直到碰到新的一行开始
fscanf(fptr,"%[^\n]", c);
printf("读取内容:\n%s", c);
fclose(fptr);
return 0;
}
输出结果为:
读取内容: runoob.com
C 语言实例
big_tree
286***4460@qq.com
参考地址
从文件中读取多行,学会使用 fgets 函数。
#include "stdlib.h" #include "stdio.h" int main(int argc, char *argv[]) { FILE *in= fopen("D:/in.java", "r"); char buf[1024]; while (fgets(buf, sizeof(buf), in) != NULL) { printf("%s", buf); } fclose(in); return 0; }同理,如果要实现,文件逐行写入到另一个文件,可以使用fputs函数即可。
改造上面的代码如下,即可:
#include "stdlib.h" #include "stdio.h" int main(int argc, char *argv[]) { FILE *in= fopen("D:/In.java", "r"); FILE *out = fopen("D:/Out.java", "w"); char buf[1024]; while (fgets(buf, sizeof(buf), in) != NULL) { fputs(buf, out); } fclose(in); fclose(out); return 0; }big_tree
286***4460@qq.com
参考地址