writing string into file before calling the close()
I am using ofstream() to write data into file, i want the program to perform such a way that it should be keep on writting the string into the file as soon as the value gets assingned to string variable, and it should be writting before calling the close().
The need is, I am getting the keystrokes of the keyboard, and i want it to be stored it in to the file... so when ever a key is pressed i want it to开发者_开发知识库 be written into the file........
can anyone help me to do that in c++.........
Call flush()
on the ofstream after writing to it. That will cause the output to be actually written instead of being buffered.
Standard C++ has no way of reading individual keystrokes from the keyboard (which I think is what you are asking about). To do this, you will need to use operating system and/or C++ implementation specific features.
Well, one option is to hang onto the std::ofstream object for the duration of the program, writing to it as needed, and then closing it at the very end of the program. Another option is to open the file in append mode each time you want to log something and close the file immediately after logging. The second option is likely to be way slower than the first, especially if you are frequently logging. If logging takes place infrequently, the second option has the advantage that you don't prevent the OS (especially if it is Windows) from doing things that it may want to do with that file. That said, I implore you to not write yet another keylogger... there are way too many of those things floating out there already... and most uses are far from legitimate.
You could subclass std::string so that it writes to a given std::ofstream each time someone makes an assignment on it:
#include <fstream>
#include <string>
class foo : public std::string
{
std::ofstream& ofs;
public:
foo(std::ofstream& ofs) : ofs(ofs) { }
foo& operator=(const std::string& string)
{
using namespace std;
if (ofs)
ofs << string << endl;
}
};
int main()
{
std::ofstream ofs("test.txt");
foo test(ofs);
test = "Write this to a file";
ofs.close();
test = "This won't be written";
}
精彩评论