0

I've been trying to grasp how reading and writing with the fstream class works, and I've become stuck. The program reads the magic number of the file correctly, and then suddenly fails to read an integer. I'm guessing I am missing something very obvious, but after several Internet searches, I've come up with nothing. If someone could point out what I'm missing, it would be extremely appreciated. Thanks!

#include <fstream>
#include <iostream>
#include "File.h"

using namespace std;

const char magicnumber[8] = {'C','H','S','R','L','I','N','E'};
const int magiclength = 8;

void saveLines(char* filename, int linenum, Line* lines){

    //Create the file and write the magic number to it
    ofstream file(filename, std::ios::trunc);
    for(int kkk = 0; kkk < magiclength; kkk++)
        file << magicnumber[kkk];

    //Write the number of lines we expect
    file << linenum;

    //Write the lines' data
    for(int iii = 0; iii < linenum; iii++){
        file << lines[iii].start.x << lines[iii].start.y;
        file << lines[iii].finish.x << lines[iii].finish.y;
        file << lines[iii].thickness;
    }

    cout << linenum << endl;
    file.close();
}

Line* openLines(char* filename){

    ifstream file(filename);
    if(!file.is_open())
        return NULL;

    //Read the magic number of the file
    char testnumber[12];
    for(int jjj = 0; jjj < magiclength; jjj++)
        file >> testnumber[jjj];

    //Make sure the file contains the right magic number
    for(int iii = 0; iii < magiclength; iii++){
        if(testnumber[iii] != magicnumber[iii])
            return NULL;
    }

    //Get the number of lines
    int linenum = -1;
    file >> linenum;
    cout << linenum << endl;
    if(linenum <= 0 || file.fail())
        return NULL;

    Line* product = new Line[linenum];
    for(int kkk = 0; kkk < linenum; kkk++){
        file >> product[kkk].start.x >> product[kkk].start.y;
        file >> product[kkk].finish.x >> product[kkk].finish.y;
        file >> product[kkk].thickness;
    }

    file.close();
    return product;
}

In the openLines() function, the file opens correctly, and the magic number is read and matched correctly, but when the variable "linenum" is read, the file reads as gibberish, the fail() flag turns true, and the function returns NULL. If it matters, here's the Line struct:

typedef struct{
    int x, y;
} Point;

typedef struct{
    float slope;
    float thickness;
    Point start;
    Point finish;
    bool defined;
} Line;

I am using SDL in this project. I do not know if this matters, but I'm including it for completeness' sake. In cout.txt I get 2 (For the linenum when I'm writing the file) and then 2147483647 when I read it back. Thanks for looking!

4

0 回答 0