简体   繁体   中英

C++: Reading and Sorting Binary Files

I've been scratching my head and putting this homework off for a couple days but now that I hunker down to try and do it I'm coming up empty. There's 4 things I need to do.

1) Read a binary file and place that data into arrays

2) Sort the list according to the test scores from lowest to highest

3) Average the scores and output it

4) Create a new binary file with the sorted data

This is what the binary data file looks unsorted

A. Smith 89

T. Phillip 95

S. Long 76

I can probably sort since I think I know how to use parallel arrays and index sorting to figure it out, but the reading of the binary file and placing that data into an array is confusing as hell to me as my book doesn't really explain very well.

So far this is my preliminary code which doesn't really do much:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;



int get_int(int default_value);
int average(int x, int y, int z);

int main() 

   {


    char filename[MAX_PATH + 1];
    int n = 0;
    char name[3];
    int grade[3];
    int recsize = sizeof(name) + sizeof(int);
    cout << "Enter directory and file name of the binary file you want to open: ";
    cin.getline(filename, MAX_PATH);    

    // Open file for binary write.
    fstream fbin(filename, ios::binary | ios::in);
    if (!fbin) {
    cout << "Could not open " << filename << endl;
    system("PAUSE");
    return -1;
   }

}

Sorry for such a novice question.

edit: Sorry what the data file stated earlier is what it SHOULD look like, the binary file is a .dat that has this in it when opened with notepad:

A.Smith ÌÌÌÌÌÌÌÌÌÌÌY T. Phillip ÌÌÌÌÌÌÌÌ_ S. Long ip ÌÌÌÌÌÌÌÌL J. White p ÌÌÌÌÌÌÌÌd

Reading a file in c++ is simple:

create a stream from file [so that to read from the stream] (you have filestream[input/output], stringstream ... )

    ifstream fin;  //creates a fileinput stream

    fin.open(fname.c_str(),ifstream::binary);        // this opens the file in binary mod  


    void readFile(string fname)
    {
        ifstream fin;
        fin.open(fname.c_str());            //opens that file;
        if(!fin)
            cout<<"err";
        string line;
        while(getline(fin,line))            //gets a line from stream and put it in line (string)
        {
            cout<<line<<endl;
            //reading every line
            //process for you need.
            ...
        }
        fin.close();
    }

as you specify, the file is simply a text file, so you can process each line and do whatever you want.

Reading from a binary file may seem confusing, but it is really relatively simple. You have declared your fstream using your file name and set it to binary, which leaves little to do.

Create a pointer to a character array (typically called a buffer, since this data is typically extracted from this array after for other purposes). The size of the array is determined by the length of the file, which you can get by using:

fbin.seekg(0, fbin.end); //Tells fbin to seek to 0 entries from the end of the stream
int binaryLength = fbin.tellg(); //The position of the stream (i.e. its length) is stored in binaryLength
fbin.seekg(0, fbin.beg); //Returns fbin to the beginning of the stream

Then this is used to create a simple character array pointer:

char* buffer = new char[binaryLength];

The data is then read into the buffer:

fbin.read(buffer, binaryLength);

All the binary data that was in the file is now in the buffer. This data can be accessed very simply as in a normal array, and can be used for whatever you please.

The data you have, however, does not at all seem binary. It looks more like a regular text file. Perhaps, unless explicitly stated, you ought to consider a different method for reading your data.

You know, with that low range of sorting index you can avoid actual sorting (with comparing indices and moving data forth and back). All you have to do is to allocate a vector of vector of strings , resize it to 101. Then traverse the data, storing each: "A. Smith" in 89-th element; "T. Phillip" in 95-th; "S. Long" in 76-th and so on.

Then by iterating the vector elements from begin() to end() you would have all the data already sorted.

It's almost linear complexity (almost, because allocation/resizing of subvectors and strings can be costly) easy and transparent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM