full code:
#include <iostream>
#include <stdio.h>
#include <string>
#include <conio.h>
using namespace std;
int main()
{
FILE* myFile;
int myNumber = 6;
string sname;
cout << "enter file name(please include file extension)\n";
cin >> sname;
if ((myFile = fopen(sname.c_str(), "w+b")) != NULL) {
fwrite(&myNumber, sizeof(myNumber), 1, myFile);
cout << "myNumber is: " << myNumber << endl;
myNumber = 0;
cout << "myNumber has been reset to 0." << endl;
fclose(myFile);
}
else
cout << "Error: File not loaded!" << endl;
if ((myFile = fopen(sname.c_str(), "r+b")) != NULL) {
cout << "Reading previous number from data.txt..." << endl;
fread(&myNumber, sizeof(myNumber), 1, myFile);
cout << "myNumber from data.txt is: " << myNumber << endl;
}
else
cout << "Error: File not loaded!" << endl;
getch();
return 0;
}
(I edited the code slightly) I managed to figure out the answer to my first question. I noticed that this now will write the number and than load it fine. however, I need to figure out how to tell it to save a string.
Also, I noticed that what it saves in the text file does not appear to be what it's loading. text file contains simply(yet it manages to load it right):
Is it suppossed to save like that?