Advertisement

Help with files =(

Started by March 15, 2002 12:46 PM
2 comments, last by Lohrno 22 years, 8 months ago
Hey can someone help me with simple binary files? I wrote this code:
  
#include "stdafx.h"
#include <stdio.h>
//#include <stdlib>
#include <conio.h>
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
struct playerscore

{
	char* name;
	int score;
};

int main(int argc, char* argv[])
{
	playerscore Score[10];

	// Part 1 --------------------------------

	char* namer = "Lalala";
	for (int i = 0;i<10;i++)
	{

		Score[i].name=namer;
		Score[i].score =50;
	}
	Score[3].name = "Fallalallalallalallalallala";
	ofstream fout("file.dat", ios::binary);
	fout.write((char *)(&Score), sizeof(Score[10]));
    fout.close();
	//Part 2 -----------------------------------

    ifstream fin("file.dat", ios::binary);
	for (int i=0;i<10;i++)
     fin.read((char *)(&Score[i]), sizeof(Score));
	for (i=0;i<10;i++)
	 cout << Score[i].name << " " << Score[i].score << endl;

    getche();
	return 0;
}

  
I run part 1 , commenting out part 2, and then run part 2, commenting out part 1. And when I run part 2, it looks like either it wrote the string badly, or it gives me some access violation errors can anyone help me? what I''m trying to do is to make it so that I can output an array of structures to a binary file, and then read them back? =D -=Lohrno

You need to actually allocate memory for the name strings, and use strcpy instead of =. Not only are you reading and writing garbage, you''re storing garbage in memory!


You also can''t just read and write entire structs when you''re using pointers inside them. If you use fixed size strings it''ll work, bot with those structs you need more complicated reading and writing.

Try using a structure like this:

{
char name[80];
int score;
};

And everywhere you do a = on a name, do a strcpy instead.
Advertisement
Wow cool it works now! Thanks anonymous guy! =D

-=Lohrno

I would suggest using the string class from the STL. It would make things like this a whole lot easier.

This topic is closed to new replies.

Advertisement