近期在使用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,里面是前面写入的六行信息。