read a txt file line by line forward or backward

I need to read a txt file line by line.
On pressing the right arrow buttton it should read the next line.
On pressing the left arrow button it should read the previous line.
The lines are not of fixed length.
platform linux
This is a help forum for beginners. How are we supposed to help you with your code when you give us nothing to work with?
The entire code is as below. the concerned lines are in bold

#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/cloud_viewer.h>
#include <iostream>
#include <fstream>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include <curses.h>
#include <iostream>
using namespace std;

#define KEY_LEFT 75
#define KEY_RIGHT 77

int main(int argc, char *argv[])
{
//create the cloud ptr
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
// create the cloud viewer
pcl::visualization::CloudViewer viewer ("Simple Cloud Viewer");
// open the file with list of pcd files
ifstream fs;
fs.open (argv[1]);
std::string current_cloud;
// while the viewer is not stopped or eof is reached update the cloudptr, show the cloud, sleep for 30ms
while (!viewer.wasStopped() )
{
if(getline (fs,current_cloud))
{
pcl::io::loadPCDFile(current_cloud,*cloud);
}
viewer.showCloud(cloud);
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
//wait for user key input, store the input
char c;
switch((c=getch())) {
case KEY_LEFT:
// reduce fileptr by 1 & read the previous line. then display the cloud
break;
case KEY_RIGHT:
// increment fileptr by 1 & read the next line
. then display the cloud
break;
default:
//cout << endl << "null" << endl; // key left
break;
}[/b]
}
fs.close();

return 0;
}
Load fs as a vector of line strings.
1
2
3
4
5
6
7
fs.open(argv[1]);
vector<string> lines;
for(string line; getline(fs, line); ) {
     lines.push_back(line);
}
fs.close();
//now you can use lines[x] to access the x+1 th line (x[0] would be the first line) 


Edit: Do not forget to #include <vector>
Also, if the file is REALLY large, you might consider only loading smaller chunks of the file.
Last edited on
Topic archived. No new replies allowed.