File Handling

Pages: 12
May 20, 2011 at 4:50pm
I had made a quiz. The quiz stores the scores of the users in a file. Now I wanted to do two things with the file. One, limit the number of lines in the file, because it will increase at a very fast rate if there is no limit.
Second, I wanted to compare the scores saved scores, so as to only keep High scores.
Can some one help me with this.

My code saves the data in file in the form:

Username: User's Name            Score:Points
May 21, 2011 at 4:25am
Someone?
May 21, 2011 at 4:34am
Just read the data from the file into some container of structures, and then just perform all the operations (sorting, deleting old entries, etc) on that container.
May 21, 2011 at 4:37am
Just read the data from the file into some container of structures, and then just perform all the operations (sorting, deleting old entries, etc) on that container.


I am not sure, but I think by structures, you are meaning data structures?
If so, how will I separate, the Points form the rest of the string?
And then also I don't know how will it limit the number of lines in the file?
May 21, 2011 at 4:39am
Do you know how to read and write to streams?
Do you know how to open file streams?
Do you know how to sort data?

Show us what you have so far (even if that's only a plan of action, but code would be nice.)
Last edited on May 21, 2011 at 4:39am
May 21, 2011 at 4:43am
I know how to read and write to streams.

I am not sure what does opening file streams mean.

And I definitely don't know how to sort data.
May 21, 2011 at 5:35am
File stream (or fstream):
http://cplusplus.com/reference/iostream/fstream
http://cplusplus.com/reference/iostream/ifstream
http://cplusplus.com/reference/iostream/ofstream

As for sorting, there are many methods and we can find the best one for this job after we come up with a game plan for your program.

Exmaple with ifstream (in file stream) and ofstream (out file stream):
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
#include <fstream>

using namespace std;

int main() {
  ofstream outFile("some_file.txt"); //opens an output stream to file "some_file.txt"
  ifstream inFile("another_file.dat"); //opens an input stream from file "another_file.dat"

  //now we can read and write to file
  outFile << "Hello, world!\n"; //writes a string to the output stream
  int data;
  inFile >> data; //reads some data from the input stream, and stores it in data
  cout << data << endl; //print the data to the standard output stream (usually the screen)

  //we can reuse are streams with new files
  outFile.close(); //we close the first stream
  outFile.open("new_file.log"); //and open a new stream to file "new_file.log"
  
  outFile << data; //let's print that data to this file too

  //it's very important to remember to close our files when we are done with them
  outFile.cloes();
  inFile.close()

  return 0;
}
Last edited on May 21, 2011 at 5:37am
May 21, 2011 at 5:51am
O.K. I know what file stream is. I actually hadn't known the technical term for it.
As for the code. It is very long.
But here is the basic structure:
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//Declerations

string name;
float score;

//Structs and fuctions for the quiz.

//The  Main program:
int main()
{
	//Data for the structs, and calls to functions:
	
	//Adding data to the Highscores file.
	
	string highscores;
	string UserName = "User Name:   ";
	string Score = "\t\tScore:  " ;
	//
	//Ading data to High scores list
	//
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		
	ofstream high_score ("high_score.txt",ios::out|ios::app);
	for (int x = 0;x < 14;x++)
	{
		UserName[x] ^= Key;
		high_score <<  UserName[x];
	}
	for (long long int x = 0;x < Name.size();x++)
	{
		Name[x] ^= Key;
		high_score<<  Name[x];
	}
	for (long long int x = 0;x < 12;x++)
	{
		Score[x] ^= Key;
		high_score << Score[x];
	}
		for (long long int x = 0;x < SCORES.size();x++)
	{
		SCORES[x]^= Key;
		high_score << SCORES[x];
	}
	high_score << "\n";
	high_score.close();

}

//Retriving Data
cout << endl << divider << "The Scores of previous users are: " << endl << endl;
		
ifstream high_scores ("high_score.txt");
while (high_scores.good())
{
	getline (high_scores,highscores);
	for (long long int x = 0; x < highscores.size();x++)
	{
		highscores[x] ^= Key;
		cout <<  highscores[x];
	}
	cout << endl;
	}
	user_score.close();


Here, Score is score of the player converted to string. I have used XOR encryption to prevent tampering with the Highscores. divider is also a string that prints 80 hyphens.
May 21, 2011 at 6:14am
So then back to your original post, limiting the number of lines stored in the file should be easy; however, you need to sort your arrays so that storing the best N scores is as easy as storing the first N scores in your array. There is plenty of documentation out there on how to sort arrays, but if you can't figure it out or need help let me know.
May 21, 2011 at 6:45am
to sort a vector simply include <algorithm> and use sort(vector[firstElemToBeSorted],vector[firstElemToBeSorted+NumberOfElementsToBeSorted])
if i am wrong please say so :-?
May 21, 2011 at 6:53am
And what is a vector??
This is the first time I have heard (or rather, read) about vectors in context of C++.
May 23, 2011 at 9:37am
Now, I have read about sorting on wikipedia, what i didn't understand is how do I specify the criteria according to which the data is to be sorted.
So how do I limit the number of lines in the file?
May 23, 2011 at 11:37am
If you are going to use vectors, each time the game is played, store the users and scores from the file in to vectors on each run of the program.

create vectors
store file data into vectors
play the game
save the scores/names into vectors
sort the vectors
use a for( loop ) to write back to the file

So, if you only want 10 high scores in the file:

1
2
3
4
for( int i = 0; i < 10; ++i )
    {
        //code to write in to file
    }


This way, you'll only have the top 10 scores.

Make sure that you use: ios::trunc with the stream. This way, all current data in the file will be deleted before writing to the file again.

ios::trunc - If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

http://www.cplusplus.com/doc/tutorial/files/
Last edited on May 23, 2011 at 11:37am
May 23, 2011 at 12:07pm
I actually hadn't intended to use vectors, since I didn't understand them.
So any help with the vectors?
May 23, 2011 at 12:25pm
Helios already gave good links for vectors.
http://www.cplusplus.com/reference/stl/vector/
http://en.wikipedia.org/wiki/Dynamic_array
http://en.wikipedia.org/wiki/Vector_(C++)


Other than that, this could also be done with arrays.
May 23, 2011 at 12:26pm
I have went through those articles, and found them hard to understand. That is why I asked for help.
May 23, 2011 at 2:58pm
I'm not one to really be helping with vectors, lol. I only started using them about a week ago and I haven't done much programming since then.

I learnt from the first link that Helios gave you, also, I just found this one that seems quite good.
http://www.dreamincode.net/forums/topic/33631-c-vector-tutorial/
May 23, 2011 at 3:12pm
Now I get the problem, the vector topic is a bit too advanced for me. I have just reached data structures in this site's tutorial.

Anyways, you said that this can also be done using arrays.
So, will the process remain the same as it was for vectors?
And if yes, then what does :
store file data into vectors

mean?
May 23, 2011 at 3:15pm
Just sort the values in an standard array. It's not that different.

All a vector is, is an array-like structure that allow the size of the array to be know and changed. Example:
Array: [ _, _, _, _, _ ] (size 5)
--add a value
[ 2, _, _, _, _ ] (size 5)
--add another value
[ 2, 9, _, _, _ ] (size 5)
...
[ 2, 9, 1, 4, 5 ] (size 5)
Vector: [] (size 0)
--add a value
[ 2 ] (size 1)
--add another value
[ 2, 9 ] (size 2)
...
[ 2, 9, 1, 4, 5 ] (size 5)
Pages: 12