C语言和mfc按格式读取文件数据

fscanf()函数的功能是从文件中按格式读取一个或多个数据;

例如文件中有一行数据,

22 3.34 hello

则使用 fscanf(fp, "%d%f%s", &a, &f, str) 可一次读取整型、浮点、字符串三个数据;

此函数位于C标准库头文件<stdio.h>中;

示例;

测试文件如下;

代码;

cpp 复制代码
void CFiletest1View::OnDraw(CDC* pDC)
{
	CFiletest1Doc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
	int a = 0;
	float f = 0;
	char str[100] = "";
	CString str1;
	int d=0;
	float f2=0;
 
	FILE* fp = fopen("test1.txt", "r");
	for(int i=0; i<3; i++)
	{
        fscanf(fp, "%d%f%s", &a, &f, str);
		str1.Format("%d,%f,%s", a, f, str);
		pDC->TextOut(50, 50 + i*20, str1);
		d += a;    
		f2 += f;
    }
	str1.Format("整数和:%d", d);
	pDC->TextOut(50, 115, str1);
	str1.Format("浮点数和:%f", f2);
	pDC->TextOut(50, 135, str1);
	fclose(fp);
}

运行如下;

在MFC中常常使用的是CStdioFile类;能否仍然可以使用fscanf()函数呢?

首先看一下,使用CStdioFile类打开文件后,返回的是BOOL类型,而fscanf需要一个FILE*类型;如果用C标准库函数fopen打开文件,返回的就是FILE*类型;

查一下MFC文档;

CStdioFile类有一个成员m_pStream,

CStdioFile::m_pStream

m_pStream数据成员是指向一个打开文件的指针,该文件是由C运行时函数fopen返回的。如果文件从来没有被打开过或者已经被关闭了,则它是NULL。

从文档说明这个m_pStream就是C标准库函数fopen打开文件后的返回值;

那么改为如下的代码看一下;

cpp 复制代码
void CFiletest1View::OnDraw(CDC* pDC)
{
	CFiletest1Doc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
	int a = 0;
	float f = 0;
	char str[100] = "";
	CString str1;
	int d=0;
	float f2=0;
 
	CStdioFile file;
	file.Open("test1.txt", CFile::modeRead);

	for(int i=0; i<3; i++)
	{
      
      //根据字符类型读取txt文件中的数据
		fscanf(file.m_pStream, "%d%f%s", &a, &f, str);
		str1.Format("%d,%f,%s", a, f, str);
		pDC->TextOut(50, 50 + i*20, str1);
		d += a;    
		f2 += f;
    }
	str1.Format("整数和:%d", d);
	pDC->TextOut(50, 115, str1);
	str1.Format("浮点数和:%f", f2);
	pDC->TextOut(50, 135, str1);
	file.Close();
}

运行一下;没有问题,一样的;

相关推荐
leaves falling11 分钟前
C++模板进阶
开发语言·c++
无敌昊哥战神27 分钟前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
坐吃山猪41 分钟前
Python27_协程游戏理解
开发语言·python·游戏
gCode Teacher 格码致知41 分钟前
Javascript提高:小数精度和随机数-由Deepseek产生
开发语言·javascript·ecmascript
椰猫子1 小时前
Javaweb(Filter、Listener、AJAX、JSON)
java·开发语言
盛世宏博北京2 小时前
以太网温湿度传感器运维技巧,提升设备稳定性与使用寿命
开发语言·php·以太网温湿度传感器
代码改善世界2 小时前
【MATLAB初阶】矩阵操作(一)
开发语言·matlab·矩阵
覆东流2 小时前
第1天:Python环境搭建 & 第一个程序
开发语言·后端·python
朝阳5813 小时前
rust 交叉编译指南
开发语言·后端·rust
量子炒饭大师3 小时前
【C++ 进阶】Cyber霓虹掩体下的代码拟态——【面向对象编程 之 多态】一文带你搞懂C++面向对象编程中的三要素之一————多态!
开发语言·c++·多态