c/c++读写txt文件一例

本文介绍使用C/C++与VS2019进行安全读写操作的方法,针对机械臂设置信息,采用fscanf_s与fopen_s函数避免安全警告。通过示例代码演示如何创建、写入并读取settings.txt文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近期在使用c/c++读写机械臂设置信息时,发现网上找到的例程大部分都使用

fscanf()
fopen()
函数而不是用的
fscanf_s()
fopen_s()

VS2019编译器因此有安全有错误提示,于是我进行了修改测试,下面是源码,实测可用:

#include<stdio.h>
#include<iostream>

// By Tom Gong 
using namespace std;



void readfile(void)
{
	
	FILE* stream;
	errno_t err;   
	long l;
	double fp;
	char s[5];
	char c='e';
	float a1, a2, d1, a3, d4, d6;
	//制作一个文件,文件名:"settings.txt",如果文件存在,就会改写其内容。
	if( ((err = fopen_s(&stream,"settings.txt", "w+"))== 0) and (stream!=0))

	{   //往"settings.txt"里面写入内容,一共六行
		fprintf(stream,
			"%s  %f \n%s  %f \n%s  %f \n%s  %f \n%s  %f \n%s  %f \n",
			"a1", 0.0,//注意一定要加小数点,写成float形式,否则系统读错
			"d1", 459.5,
			"a2", 680.0,//注意整数一定要加小数点,写成float形式,否则系统读错
			"a3", 0.0,
			"d4", 680.0,
			"d6", 284.5 );
//读取文件并在控制台打印出来。
		fseek(stream, 0L, SEEK_SET);
		fscanf_s(stream,"%s",s,sizeof(s));
		fscanf_s(stream, "%f", &a1);
		printf("%s ", s);
		printf("%f\n", a1);

		fscanf_s(stream, "%s", s, sizeof(s));
		fscanf_s(stream, "%f", &d1);
		printf("%s ", s);
		printf("%f\n", d1);

		fscanf_s(stream, "%s", s, sizeof(s));
		fscanf_s(stream, "%f", &a2);
		printf("%s ", s);
		printf("%f\n", a2);

		fscanf_s(stream, "%s", s, sizeof(s));
		fscanf_s(stream, "%f", &a3);
		printf("%s ", s);
		printf("%f\n", a3);

		fscanf_s(stream, "%s", s, sizeof(s));
		fscanf_s(stream, "%f", &d4);
		printf("%s ", s);
		printf("%f\n", d4);

		fscanf_s(stream, "%s", s, sizeof(s));
		fscanf_s(stream, "%f", &d6);
		printf("%s ", s);
		printf("%f\n", d6);


		fclose(stream);
	}
}


int main()
{
	readfile();
	
	Sleep(63000);
}

系统运行后,会生成一个文件settings.txt,里面是前面写入的六行信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值