So i'm making an extremely simple guessing console game and i want to store data permanently in a file (highscore). However everytime i compile the file i'm using empties itself. Is there anyway to stop that?
I've tried a lot of thing which didn't work and i honestly don't know where the problem is. I'm guessing it has to do with the fin and fout but for others it seemed to work
#include <iostream>
#include <fstream>
#include <time.h>
#include <conio.h>
int hs;
//this would be the play_game() function, unrelated to the subject
int main()
{
std::ofstream fout;
fout.open("HS.txt");
std::ifstream fin;
fin.open("HS.txt");
srand(time(NULL));
//menu with 4 options, play, quit, help and highscore (which i'm working on)
fin.close();
fout.close();
}
Don't open your file twice in parallel with two streams. Also, a simple open-for-writing will not truncate your file, but will place you at the start of the file, so you'll be overwriting existing data; see this question. You have to open files with the write mode.
You need to either:
Open your file for both input and output - and without truncating it; see: What does it mean to open an output file as both input and output? , or
Open your file for reading only when your app starts, and open it for writing, and write to it, when it exists (or every once-in-a-while for better resiliency).
Related
I have a problem where ofstream isn't creating a text file. I compile and run the program just fine with no errors and I am 100 percent certain that I am in the right directory and that there are no spelling mistakes or errors. What is strange is when I move my program to my C drive or onedrive folder, then the text file is created, it just doesn't work in any of my other folders. I don't know what the problem is and I have scoured the internet for the past couple hours trying to find a solution, but I think it has something to do with my file permissions perhaps?
Here is my code, it's just a really simple program:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream myfile;
myfile.open("newnumbers.txt");
}
I want to create a database in a txt file and access it and edit certain parts of it using seekp(), but when I open the file to write in it , the program creates a new file deleting the previous one.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream g;
g.open("text.txt",ios::out);
if(!g.is_open())
cout<<"error";
else {
g.seekp(2);
g.write("apple",5);
}
g.close();
return 0;
}
You'll need a different open mode.
The documentation is quite obscure when it comes to the behavior of ofstream (for all practical purposes, the behavior you observe is by design: it will truncate).
Use fstream with ios_base::in | ios_base::out | ios_base::binary instead.
Unless you're using some encoding where one character is always one, two, or four bytes, you won't be able to consistently do this with a text mode. Also, writing at any seek position before end-of-file won't shift content past the current seek position, it is simply overwritten. So in order to achieve a database-like behavior, you're at least going to need some kind of fixed-size records or an indexing data structure.
I was just learning C++ file handling, but ran into an error immediately using this simple code to create a new file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file("test.txt");
file << "test";
file.close();
}
File doesn't show up. When I use .is_open(), it always gives 0. Program does compile though.
Then I manually created a .txt file with some text and tried to read it, and it worked. I supposed it was permission thingy, but it seems like all files are available to be changed? I'm not sure I completely understand how to check the permission though (I'm a bit new to all of this...), so please do help with it as well!
I use Atom and its terminal, my compiler is MingW, but I guess it might be a bit too old.
I tried to include the whole path, but it didn't work.
Thank you!
EDIT:
Just tried this code:
ofstream file;
file.open("C:\\Users\\username\\Desktop\\my_folder\\test.txt");
file << "test";
file.close();
Doesn't help. .is_open() gives 0 before I even try to write to a file.
EDIT:
Just tried this code:
fstream fileW;
fileW.open("write.txt", ios_base::in | ios_base::out | ios_base::trunc);
cout<<fileW.fail()<<endl;
cout<<fileW.is_open()<<endl;
fileW<<"Edit";
fileW.close();
Still doesn't work, returns 1 for .fail().
EDIT:
The error is "Permission denied".
EDIT:
Solved! I deleted Avast, it was blocking my program from accessing files.
Avast, I hate you. You are the worst.
Use
ofstream file("test.txt");
Your version does not create the file if it does not exist.
Similarly for input you should really use ifstream. fstream is best reserved for files you want to read and write from.
I am working with Xcode and I am having trouble opening a file stream to assign variables from a text file. I speculate that placing the txt file in the same directory as the project would allow me open the stream without including the entire dir. I have been messing with this for a little while to no avail can I get it to work properly. I believe I was able to read data at one point, but I think the string printed was in unicode (not sure). It is a very simple program.. I would think that it would work.
I think my problem has to do with the directory the example is in and how Xcode works with project files. I just put the example file in the project folder and hoped that it would work.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name;
ifstream infile;
infile.open("example.txt");
if(infile.is_open())
{
infile >> name;
}
else
cout << "Unable to open file";
cout << name;
return 0;
}
First of all, remember, that working directory is not always the same directory where the program's binary resides.
Change:
infile.open("example.txt");
to:
infile.open("/full/path/to/program/directory/example.txt");
where /full/path/to/program/directory/ is the location of folder, where program (and thus example.txt file) is placed. It should fix the issue.
By the way, you may also want to read this question, that addresses very similar problem.
Also, read about getcwd() function.
The program almost runs but i am not sure how to make the .txt file for this , its not giving me an error.
the project asks me to:
" File encryption is the science of writing the contents of a file in a secret code. Your encryption program should work like a filter, reading the contents of one file, modifying
the data into a code, and then writing the coded contents out to a second file.
The second file will be a version of the first file, but written in a secret code. Although there are complex encryption techniques, you should come up with a simple one of your own. For example, you could read the first file one character at a time, and add 10 to the ASCII code of each character before it is written to the second file. "
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
fstream fin, fout;
fin.open("testone.txt", ios::in);
fout.open("encrypted.txt", ios::out);
while (!fin.eof())
{
fin.get(ch);
fout.put(ch + 10);
}
fin.close();
fout.close();
system("pause");
return 0;
}
Read this -
Error LNK1561: entry point must be defined
https://social.msdn.microsoft.com/Forums/vstudio/en-US/e1200aa9-34c7-487c-a87e-0d0368fb3bff/error-lnk1561-entry-point-must-be-definedproblem-in-c?forum=vclanguage
Not up on my Visual C, but you may need #include <cstdlib> to get system
LNK1561 means your main function can't be found. Clearly the main function is present, so this should compile. Follow Beta's suggestion and ensure you can compile and run a trivial program.
Putting Compiling issues aside, This code won't work.
Overarching Problem: You are not checking for any errors along the way, so there is no way for your program to tell if anything has gone wrong.
For example, what if the file didn't open? The while (!fin.eof()) becomes an infinite loop. If the file is not open, you can never read EOF. Trying to use EOF as a loop condition is a bad idea anyway. Definitely read the link in #Steephen's comment.
If you fail to read a character with fin.get(ch); then what? The current code tries to use the character anyway. Bad idea.
Testing a stream is pretty simple. if (!fin) does the job. Read up on how streams work to learn why. Thius simple test doesn't tell you what went wrong, but at least you know something went wrong.
To make things easier, most stream functions return the stream. This lets you chain stream operations together and makes if (!fin.get(ch)) an easy way to tell if get worked.
So your IO loop can be as simple as
while (fin.get(ch) && fout.put(ch + 10))
{
}
If get couldn't get ch for any reason--unopened file, end of file, unreadable file--the while loop exits. Afterwards you can query fin to find out why. If EOF, awesome. If not EOF, the output file's probably wrong.
The same applies to put. If put failed, the loop ends. Test for why and decide if you want to keep the file.
I also recommend dropping a quick test at the end of main to print out a check.
fin.open("encrypted.txt", ios::in);
while (fin.get(ch) && std::cout.put(ch - 10))
{
}
A better test would be to read the character, undo the encryption, and compare against the original input.