2026-02-25 04:22:41C 语言实例 - 从文件中读取一行
从文件中读取多行,学会使用 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 big_tree
286***[email protected]
参考地址
7年前 (2019-08-02)