C++中文件读写操作及文件中指定内容的获取
-
-
- 1、目的
- 2、代码
- 3、操作接口函数
-
1、目的
从文件中(文件格式如下图)获取x,y的数值,存储到形参argv传输过来的地址中;并输出到txt文本中。
2、代码
通过c++的实现代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <stdlib.h>
using namespace std;
int GetCoordinate(char *Filename, float argv[][2])
{
int Begin, End;
string X, Y;
string Line;
static char num = 0;
ifstream inFile;
ofstream outFile;
inFile.open(Filename); //打开文件用于读取数据。如果文件不存在,则打开出错。
if (!inFile.is_open()) //判断文件是否成功打开
{
cout << "Error opening file" << endl;
return 1;
}
outFile.open("GetCoordinate.txt");//打开文件用于写入数据
while (!inFile.eof())
{
getline(inFile, Line); //获取一行的数据,存放到Line中
if ((Begin = Line.find("x=")) != string::npos)//若该行中存在"x="的字符
{
Begin += 2;
if (Begin == Line.find('"')) //若"x="的下一个字符是'"',则定位到了数据开始的位置
{
End = Line.find('"', Begin + 1);//定位x坐标文本的结束下标
X = Line.substr(Begin + 1, (End - (Begin + 1)));//获取x坐标的文本信息
argv[num][0] = atof(X.c_str()); //将字符类型转换为浮点类型存储
outFile << 'x' << (num + 1) << ": " << argv[num][0] << "\n";//输出到文本
}
}
if ((Begin = Line.find("y=")) != string::npos)
{
Begin += 2;
if (Begin == Line.find('"', Begin))
{
End = Line.find('"', Begin + 1);
Y = Line.substr(Begin + 1, (End - (Begin + 1)));
argv[num][1] = atof(Y.c_str());
outFile << 'y' << (num + 1) << ": " << argv[num][1] << "\n";
outFile << "\n";
num++;
}
}
}
inFile.close();
outFile.close();
return 0;
}
3、操作接口函数
- while (!inFile.eof()):判断是否读取到文件(inFile)结尾处;
- getline(inFile, Line):读取inFile,直到遇到换行符(’\n’)时结束(结束符也可以自己定义,是函数的第三个参数,默认为换行符),将数据存储到Line中;
- End = Line.find(’"’, Begin + 1):在Line中从(Begin+1)的位置开始,查找第一次出现’"'的位置;将字符下标存放到End;
- X = Line.substr(Begin + 1, (End - (Begin + 1))):获取Line中,从(Begin+1)位置开始,(End - (Begin + 1))个字符的子串信息;存储到X中;
- atof(X.c_str()):将X这个字符串中的数字信息转换为浮点型数(该函数会自动跳过前面的空格字符(但不能跳过前面的其他字符),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(’\0’)才结束转换,并将结果返回)