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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
// Create athletes object file
// Prueba usando char[20] en vez de string
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Class to define the properties
class Athletes {
public: // Instance variables
char AName[20]; // athlete name
int AAge; // athlete age
public: // Methods
int createFile(); // Function to create file
int readFile(); // Function to read file
};
int Athletes::createFile() { // Athletes: create file rutine
ofstream AFile; // output file
AFile.open("/sdcard/Download/C_C++/Athletes.txt", ios::out);
printf ("Open output status: %d\n\n", AFile.rdstate());
Athletes a1;
strcpy(a1.AName,"Peter"); a1.AAge=21;
AFile.write((char*)&a1, sizeof(a1));
printf ("Write status: %d Fields: %s %d\n",
AFile.rdstate(), a1.AName, a1.AAge);
memcpy(a1.AName,"John", 9); a1.AAge=23; // In these line I test with number of character to copy
AFile.write((char*)&a1, sizeof(a1));
printf ("Write status: %d Fields: %s %d\n",
AFile.rdstate(), a1.AName, a1.AAge);
cout << endl;
AFile.flush();
AFile.close();
return 0;
}
int Athletes::readFile() { // Athletes: read file rutine
ifstream AFile; // read file
AFile.open("/sdcard/Download/C_C++/Athletes.txt", ios::in);
printf ("Open input status: %d\n\n", AFile.rdstate());
Athletes a1;
AFile.read((char*)&a1, sizeof(a1));
printf ("Read status : %d ", AFile.rdstate());
printf ("athlete's name: %s age: %d\n", a1.AName, a1.AAge);
AFile.read((char*)&a1, sizeof(a1));
printf ("Read status : %d ", AFile.rdstate());
printf ("athlete's name: %s age: %d\n", a1.AName, a1.AAge);
cout << endl;
AFile.close();
printf ("Read status : %d\n", AFile.rdstate());
return 0;
}
int main() {
// Creating object of the class
Athletes obj;
// Processing the data
obj.createFile();
obj.readFile();
printf ("Program ended");
return 0;
}
| |