我一直在努力了解fstream课程的阅读和写作是如何工作的,而且我已经陷入困境。程序正确读取文件的幻数,然后突然无法读取整数。我猜我错过了一些非常明显的东西,但经过几次互联网搜索,我什么也没想到。如果有人能够指出我所缺少的东西,那将非常感激。谢谢!
#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;
}
在openLines()函数中,文件正确打开,并且正确读取和匹配幻数,但是当读取变量“linenum”时,文件读作乱码,fail()标志变为true,并且该函数返回NULL。如果重要,这里是Line结构:
typedef struct{
int x, y;
} Point;
typedef struct{
float slope;
float thickness;
Point start;
Point finish;
bool defined;
} Line;
我在这个项目中使用SDL。我不知道这是否重要,但我是为了完整而包括它。在cout.txt中,我得到2(当我写文件时为亚麻布),然后当我读回时为2147483647。谢谢你的期待!