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’)才結束轉換,并将結果傳回)