使用txt文档注意及时关闭打开

在进行txt文件数据处理时,必须确保及时关闭文件以避免读取错误。此C++程序演示了如何从txt文件读取点云数据并转换为pcd格式,强调了文件关闭的重要性。

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

在使用txt文档数据的时候,注意及时关闭,否则容易出错。下面的程序是实现txt数据转换成pcd数据的另一种方法,参考网上其他人修改的

#include<iostream>
#include<fstream>
#include <string>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
using namespace std;
int main()
{
struct lin
     {
       double a[3];
      };
//////以下为计算txt文件中点的数量//////////
int n = 0;
int c = 0;
FILE *fp_txt;
fp_txt = fopen("C:/Users/can/Desktop/PCL test/txt2pcd/test.txt", "r");
if (fp_txt == NULL)
{
cout << "无法打开文件" << endl;
return 0;
}

do{
c = fgetc(fp_txt);
if (c == '\n')
{
++n;
}
} while (c != EOF);
std::cout << "Total points: " << n << std::endl;
//不关闭txt的话,下面的fscanf()函数接着往下读取,读不出来数据!!!!!!
fclose(fp_txt);
//关闭以后需要重新打开
fp_txt = fopen("C:/Users/can/Desktop/PCL test/txt2pcd/test.txt", "r");
lin * st_1 = new lin[n];

    for(int i=0; i<n; ++i)
{
fscanf(fp_txt, "%lf %lf %lf", &st_1[i].a[0], &st_1[i].a[1], &st_1[i].a[2]);
    }
    
    std::cout<<"Read data is ok!"<<std::endl;
    pcl::PointCloud<pcl::PointXYZ> cloud;
// Fill in the cloud data
cloud.width    = n;
cloud.height   = 1;
cloud.is_dense = false;
cloud.points.resize (cloud.width * cloud.height);
for (size_t i = 0; i < cloud.points.size (); ++i)
{
cloud.points[i].x = st_1[i].a[0];
cloud.points[i].y = st_1[i].a[1];
cloud.points[i].z = st_1[i].a[2];
}
pcl::io::savePCDFileASCII ("C:/Users/can/Desktop/PCL test/txt2pcd/txt2pcd.pcd", cloud);
std::cerr << "Saved " << cloud.points.size () << " data points to txt2pcd.pcd." << std::endl;
for (size_t i = 0; i < cloud.points.size (); ++i)
   std::cerr << "    " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
delete[] st_1;
system("pause");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值