0
点赞
收藏
分享

微信扫一扫

C语言 读取文件内容

读取文件文本内容:

要读取的目标文件:
C语言 读取文件内容_数据
要读取的目标内容:
C语言 读取文件内容_#include_02
运行前请将代码文件和要读取的文件放在同一目录下。

#include <stdio.h>

int&nbsp;main(void){
int&nbsp;ch;
FILE&nbsp;*fp;
char&nbsp;fname[FILENAME_MAX];

printf(&quot;文件名:&quot;);
scanf(&quot;%s&quot;,&nbsp;fname);

if((fp&nbsp;=&nbsp;fopen(fname,&nbsp;&quot;r&quot;))&nbsp;==&nbsp;NULL){
printf(&quot;文件打开失败。\n&quot;);
}&nbsp;else&nbsp;{
while&nbsp;((ch&nbsp;=&nbsp;fgetc(fp))&nbsp;!=&nbsp;EOF){
putchar(ch);
}
fclose(fp);
}

return&nbsp;0;
}

运行结果:
C语言 读取文件内容_字符串_03

#define FILENAME_MAX 1024;
在该运行环境中保证能够打开文件,保持这样的文件名的最大长度所需的数组元素个数。

fgetc函数:

头文件

原型

说明

返回值

#include <stdio.h>

int fgetc(FILE *stream);

从stream指向的输入流(若存在)中读取unsigned char型的下一个字符的值,并将它转换为int型,然后,若定义了流的文件位置指示符,则将其向前移动。

返回stream所指输入流中的下一个字符。若在流中检查到文件末尾,则设置该流的文件结果指示符并返回EOF。如果发生读取错误,就设置该流的错误只是符并返回EOF。

当从文件正常读取到字符时,就会进入 while 循环语句,通过 putchar(ch) 语句将读取到的字符 ch 显示界面上。
当达到文件末尾(后面没有字符)或者有错误发生时,就会结束 while 语句循环并关闭文件,程序结束运行。

读取文件数据内容:

要读取的数据内容:
C语言 读取文件内容_#include_04

#include <stdio.h>

int&nbsp;main(void){
FILE&nbsp;*fp;
int&nbsp;count&nbsp;=&nbsp;0;
char&nbsp;name[100];
double&nbsp;height,&nbsp;weight;
double&nbsp;hsum&nbsp;=&nbsp;0.0;
double&nbsp;wsum&nbsp;=&nbsp;0.0;

if&nbsp;((fp&nbsp;=&nbsp;fopen(&quot;students.txt&quot;,&nbsp;&quot;r&quot;))&nbsp;==&nbsp;NULL){
printf(&quot;\a文件打开失败。&nbsp;\n&quot;);
}&nbsp;else&nbsp;{
while&nbsp;(fscanf(fp,&nbsp;&quot;%s%lf%lf&quot;,&nbsp;name,&nbsp;&amp;height,&nbsp;&amp;weight)&nbsp;==&nbsp;3){
printf(&quot;%-10s&nbsp;%5.1f&nbsp;%5.1f\n&quot;,&nbsp;name,&nbsp;height,&nbsp;weight);
count++;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// 计算数据的条数
hsum&nbsp;+=&nbsp;height;&nbsp;&nbsp;// 对身高求和
wsum&nbsp;+=&nbsp;weight;&nbsp;&nbsp;// 对体重求和
}
printf(&quot;-------------------------\n&quot;);
printf(&quot;平均&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%5.1f&nbsp;%5.1f\n&quot;,&nbsp;hsum&nbsp;/&nbsp;count,&nbsp;wsum&nbsp;/&nbsp;count);
fclose(fp);
}

return&nbsp;0;
}

运行结果:
C语言 读取文件内容_#include_05
fscanf函数:

头文件

原型

说明

返回值

#include <stdio.h>

int fscanf(FILE *stream, const char *format, …);

从stream指向的流(而不是从标准输入流)中读取数据。将读取的数据格式转换,并将转换结果保存至format后面的实参所指向的对象。format指向的字符串为格式控制字符串,它指定了可输入的字符串及其赋值时转换方法。格式控制字符串中可以不包含任何命令,也可包含多个命令。

若没有执行任何转换就发生了输入错误,则返回宏定义EOF的值。否则,返回成功赋值的输入项数。若在输入中发生匹配错误,则返回的输入项数会少于转换说明符对应的实参个数,甚至为0。

fscanf(fp,&nbsp;&quot;%s%lf%lf&quot;,&nbsp;name,&nbsp;&amp;height,&nbsp;&amp;weight);

从流 fp 中读取1个字符串和2个double型实数,分别将它们保存至变量 name、height 和 weight中。

注:scanf 函数 和 fscanf函数会返回读取到的项目数。

该程序中,当正常读取到姓名、身高、体重项目返回 3时,就会继续while 语句循环直至读取不到信息(已读取完所有信息,或因出错而不能进行读取)。


举报

相关推荐

0 条评论