binary

closed account (4wpL6Up4)
Hi, I am supposed to write a program that reads the binary file timelog.dat and saves all data from the sensor A into the text file
A.txt. The rest of the data should be ignored.
This is what I came up with so far but I am not sure how to move forward.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #include "pch.h"
#include <iostream>
#include <fstream>
#include <string>

#define SIZE_BUF   15
using namespace std;
struct DataRecord
{
	char logger;
	double temp;
	time_t locTime;
};

void main()
{
	char bFileName[] = "timelog.dat";
	char chr[800];

	ifstream  iFile(bFileName, ios::binary);
	iFile.read((char *)(&chr), sizeof(chr));
	iFile.close();

	cout << chr << endl;
	cin.get();
	return;
}
> void main()
main returns int, not void.

Perhaps
1
2
3
4
5
DataRecord data;
iFile.read((char *)(&data), sizeof(data));
cout << "Log=" << data.logger
     << ", Temp=" << data.temp
     << ", time=" << data.locTime << endl;
Not clear from your description DataRecord.logger corresponds to multiple sensors.
If that's the case, then you need an if statement to test if DataRecord is from sensor A.

Your code reads only a single character from the file. Presumably, timelog.txt has multiple records, possibly from multiple sensors. Therefore you need to read complete DataRecords in a loop, test if from sensor A, and if true, write to A.txt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

struct DataRecord
{
    char logger;
    double temp;
    time_t locTime;
};

int main()
{
    ifstream    ifile("timelog.dat", ios::binary);
    ofstream    ofile("A.txt", ios::binary);
    DataRecord  rec;

    while (ifile.read((char *)&rec, sizeof(rec)))
    {
        if (rec.logger == 'A')
            ofile.write((char *)&rec, sizeof(rec));
    }
    ifile.close();
    ofile.close();
    cin.get();
    return 0;
}


Edit: corrected errors in code
Last edited on
closed account (4wpL6Up4)
Thanks for the hints, however, your code is full of mistakes once I try to run it.
I have tried to polish it but the errors keep popping up.
Perhaps you can provide a cleaner version?
How about you post your latest code.
Along with whatever error messages you're getting.
Corrected errors in the code above. Sorry. I thought I had a clean compile.

Topic archived. No new replies allowed.