读写文件是编程中常用的基本操作,下面给出C++中使用 FILE 读、写、追加写文件的例子:
1、读取vertices.txt文件中的平面点坐标,文件内容如下
v 0.0,0.0
v 1.0,0.0
v 0.0,1.0
v 1.0,1.0
2、坐标写到新的文件vertices_copy.txt里
3、vertices_copy.txt尾部追加面信息
#include <iostream>
#include <vector>
using namespace std;
// 平面点结构体
struct Point2f {
float x;
float y;
};
// 三角面结构体
struct Face {
int v0, v1, v2;
};
// 读文件
bool ReadFile(const char* filename, vector<Point2f>& vertices) {
vertices.clear();
FILE* fp = nullptr;
fopen_s(&fp, filename, "r"); // 以读的方式打开
if (fp != nullptr) {
Point2f point;
char strline[1024];
while (fgets(strline, sizeof(strline), fp) != nullptr) {
printf("%s", strline);
sscanf_s(strline, "v %f,%f\n", &point.x, &point.y);
vertices.push_back(point);
}
// or
/*while (!feof(fp