C++ only natively supports file access through iostreams. You create an object of the *fstream family of classes and open them using a file name and orientation. To open a file for reading you would probably do this:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream file("file");
if (file.is_open()) {
std::string s;
while (getline(file, s))
std::cout << s << '\n';
}
} To write to a file, you use ofstream instead of ifstream, and the corresponding operators:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream file("file");
std::ofstream log("log");
if (file.is_open()) {
std::string s;
while (getline(file, s)) {
std::cout << s << '\n';
log << s << '\n';
}
}
} Along with unidirectional streams, you can also have a bidirectional stream that allows input and output with intervening flushes or seeks:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream file("file", std::ios::in | std::ios::out);
if (file.is_open()) {
file << "First line\nSecond line" << '\n';
file << "Third line" << '\n';
file.seekg(0, std::ios::beg);
std::string s;
while (getline(file, s))
std::cout << s << '\n';
}
} Once opened, file streams are used just like cin and cout unless they're bidirectional. In that case you also have to consider the flush or seek when you change direction so that the stream buffer is synchronized. Otherwise, even the bidirectional file streams are used just like cin and cout.
Timers are tricky. If you need good precision, ie. REALLY every N seconds rather than just an approximation of every N seconds, then you'll probably have to resort to some platform dependent function like the Windows API Sleep() or Unix sleep(). You can get pretty good precision with the standard C++ library , but it requires a busy loop using the tm struct. Otherwise you're just guessing or relying on a non-portable representation of time_t. I'd recommend just using a platform dependent function. :)