RSS Forums RSS
Please support our C++ advertiser: Programming Forums

write and read to file

Join Date: Oct 2007
Posts: 23
Reputation: fmufti is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 0
fmufti fmufti is offline Offline
Newbie Poster

Re: write and read to file

  #9  
Oct 19th, 2007
Thanks to all of you. However, the problem is not fully over, as I mentioned that actual data will from sensor so I need to keep writing the frames till the user press some key e.g 's'.
1. How to do that ?
2. How to put the frame no before each dist and ampl arrays are written.
3. And to read them
I have put my my code as
#include "stdafx.h"
#include<iostream>
#include<stdio.h>
#include <conio.h>
#include<fstream>
using namespace std;


void WriteToFile(const char *filename, int ArraySize);
void ReadFromFile(const char *filename, int ArraySize);
int _tmain(int argc, _TCHAR* argv[])
{
	char what;
	static const char filename[] = "data.dat";
	int ArraySize=10;
	std::cout<<"To Write: 'w' and press 's' to stop, To Read 'r'"<<endl;
	std::cin>>what;
	if (what=='w'){
		WriteToFile(filename, ArraySize);}
	else if (what=='r'){
		ReadFromFile(filename, ArraySize);}
	else exit(1);
	return 0;
}
void WriteToFile(const char *filename, int ArraySize)
{
	double c[10]={1,2,3,4,5,6,7,8,9,10};
	double d[10]={5,6,7,8,9,4,3,2,3,4};
	double *dist=c;
	double *ampl=d;
	char stop;
	
			std::ofstream fileout(filename,ios::out | ios::binary );
			if(!fileout) {std::cout << "Cannot open file to write.\n"; }
		//Some function will provide dist and ampl value for each frame;
			while(kbhit())
			{
 		    fileout.write((char *) dist, sizeof(double)*ArraySize);  
		    fileout.write((char *) ampl, sizeof(double)*ArraySize);
			}
 		    fileout.close();
	
	 }
 void ReadFromFile(const char *filename, int ArraySize)
 {
	int i;
	double *read_dist=new double[ArraySize];
	double *read_ampl=new double[ArraySize];
	 ifstream filein(filename, ios::in | ios::binary); 
		if(!filein) {   
		std::cout << "Cannot open file to read.\n"; } 
		filein.read((char *) read_dist, sizeof( double ) * ArraySize );
		filein.read((char *) read_ampl, sizeof( double ) * ArraySize ); 

     for(i = 0; i <ArraySize; i++) 
	 {
	 std::cout << "Distance: "<<read_dist[i] <<endl; 
	 std::cout << "Amplitude: "<<read_ampl[i] <<endl; 
	 }
   filein.close();
   delete [] read_dist;
   delete [] read_ampl;
 }

Thanks
Last edited by fmufti : Oct 19th, 2007 at 11:22 am.
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 2:16 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC