Hi, I'm learning some stuff about file streams.
What is the best way to create a file (if it doesn't exist), then read from it, then write to it?
Doing fstream only works if the file already exists.
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
std::fstream f;
f.open("count.dat");
if (!f.is_open())
{
//This runs when count.dat does not exist yet.
std::cout << "Error opening file..." << std::endl;
return -1;
} else std::cout << "File opened." << std::endl;
f.close();
}
|
In the code above, using std::fstream only works if count.dat
already exists.
To actually make a file, it appears that I have to use std::ostream.
Here's the full code:
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
|
#include <iostream>
#include <fstream>
#include <cstdlib>
/**
* Keeps track of how many times this program has run,
* using count.dat as a source of "memory" for it.
*/
int main()
{
std::fstream f;
f.open("count.dat");
if (!f.is_open())
{
std::cout << "Error opening file..." << std::endl;
return -1;
} else std::cout << "File opened." << std::endl;
std::string line = "";
int n = 0; //initialized to zero, in case first time running the file.
while(getline(f, line))
{
std::cout << "Line: " << line << std::endl;
n = std::stoi( line );
//n = atoi(line.c_str());
}
f.clear(); //Resets EOF so that it can write again
f.seekg(0); //Resets reading file back to index 0
n++;
f << n;
f.close();
return 0;
}
|
In the code above, count.dat will either be empty, or have an integer number in it.
Can anyone give me a good way to make it so the above code will *create* count.dat if it does not already exist, but still be able to read and write to it?
Also, it's not important, but why does my program not return -1 after it displays "Error opening file..."? It says it returned with some junk 42929...whatever value.