can anyone tell me what's wrong with this?
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
class writeManager
{
std::vector<double> valueVector;
std::ofstream ofsFile;
public:
writeManager(void);
void writeOnFile(int);
void openOfsStreams(void);
void closeOfsStreams(void);
};
writeManager::writeManager(void)
{
openOfsStreams();
ofsFile << "FIRST LINE" << std::endl;
closeOfsStreams();
}
void writeManager::writeOnFile(int input)
{
openOfsStreams();
if(ofsFile.good())
{
ofsFile << input << std::endl;
}
else
{
std::cout << "Hey!" << std::endl;
}
ofsFile.close();
}
void writeManager::openOfsStreams(void)
{
ofsFile.open("/home/user/example.txt");
}
void writeManager::closeOfsStreams(void)
{
ofsFile.close();
}
int main()
{
writeManager writeObject;
for (unsigned int i = 0; i!= 5; i++)
{
writeObject.writeOnFile(i);
}
}
I'd like to see this output on file "example.txt"
FIRST LINE
0
1
2
3
4
but I get only
4
PS: no "Hey!" is printed.
The problem is that you open and close the file multiple times and each time you open the file you destroy the contents that were there previously.
Probably you should open the file once only in the constructor (and don't close the file there).
An alternative would be to open the file in 'append' mode, but that would be very inefficient, opening a file is an expensive operation. As Liho suggested
ofsFile.open("/home/user/example.txt", std::ofstream::out | std::ofstream::app);
When you open your ofstream multiple times, it always rewrites it from the beginning.
One of the possible solutions would be to use app flag, i.e. change:
ofsFile.open("/home/user/example.txt");
to
ofsFile.open("/home/user/example.txt", std::ofstream::out | std::ofstream::app);
Yet even better would be to open this ofstream just once in constructor and close it in destructor.
Related
I'm trying to figure out how to write to a file outside the working directory. This is the code I currently have.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string sp{};
std::fstream ss("C:\\Users\\onion\\AppData\\Roaming\\MetaQuotes\\Terminal\\some numbers\\MQL5\\Files\\testnew.txt", std::ios::in | std::ios::out);
if (!ss.is_open()) std::cout << "Failed" << '\n';
else
{
while (ss.is_open())
{
std::getline(ss, sp);
std::cout << sp << '\n';
ss << "new data";
if (ss.eof())break;
}
}
}
I can read the file perfectly fine, but I cant write to it? Could it be that Metatrader itself is limiting my ability to write to a file or does a file have to be in the working directory to be able to write to it? or am I just doing it wrong?
I want to create a small code in C++ with the same functionality as "tail-f": watch for new lines in a text file and show them in the standard output.
The idea is to have a thread that monitors the file
Is there an easy way to do it without opening and closing the file each time?
Have a look at inotify on Linux or kqueue on Mac OS.
Inotify is Linux kernel subsystem that allows you to subscribe for events on files and it will report to your application when the even happened on your file.
Just keep reading the file. If the read fails, do nothing. There's no need to repeatedly open and close it. However, you will find it much more efficient to use operating system specific features to monitor the file, should your OS provide them.
Same as in https://stackoverflow.com/a/7514051/44729 except that the code below uses getline instead of getc and doesn't skip new lines
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
static int last_position=0;
// read file untill new line
// save position
int find_new_text(ifstream &infile) {
infile.seekg(0,ios::end);
int filesize = infile.tellg();
// check if the new file started
if(filesize < last_position){
last_position=0;
}
// read file from last position untill new line is found
for(int n=last_position;n<filesize;n++) {
infile.seekg( last_position,ios::beg);
char test[256];
infile.getline(test, 256);
last_position = infile.tellg();
cout << "Char: " << test <<"Last position " << last_position<< endl;
// end of file
if(filesize == last_position){
return filesize;
}
}
return 0;
}
int main() {
for(;;) {
std::ifstream infile("filename");
int current_position = find_new_text(infile);
sleep(1);
}
}
I read this in one of Perl manuals, but it is easily translated into standard C, which, in turn, can be translated to istreams.
seek FILEHANDLE,POSITION,WHENCE
Sets FILEHANDLE's position, just like the "fseek" call of
"stdio".
<...>
A WHENCE of 1 ("SEEK_CUR") is useful for not moving the file
position:
seek(TEST,0,1);
This is also useful for applications emulating "tail -f". Once
you hit EOF on your read, and then sleep for a while, you might
have to stick in a seek() to reset things. The "seek" doesn't
change the current position, but it does clear the end-of-file
condition on the handle, so that the next "<FILE>" makes Perl
try again to read something. We hope.
As far as I remember, fseek is called iostream::seekg. So you should basically do the same: seek to the end of the file, then sleep and seek again with ios_base::cur flag to update end-of-file and read some more data.
Instead of sleeping, you may use inotify, as suggested in the other answer, to sleep (block while reading from an emulated file, actually) exactly until the file is updated/closed. But that's Linux-specific, and is not standard C++.
I needed to implement this too, I just wrote a quick hack in standard C++. The hack searches for the last 0x0A (linefeed character) in a file and outputs all data following that linefeed when the last linefeed value becomes a larger value. The code is here:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int find_last_linefeed(ifstream &infile) {
infile.seekg(0,ios::end);
int filesize = infile.tellg();
for(int n=1;n<filesize;n++) {
infile.seekg(filesize-n-1,ios::beg);
char c;
infile.get(c);
if(c == 0x0A) return infile.tellg();
}
}
int main() {
int last_position=-1;
for(;;) {
ifstream infile("testfile");
int position = find_last_linefeed(infile);
if(position > last_position) {
infile.seekg(position,ios::beg);
string in;
infile >> in;
cout << in << endl;
}
last_position=position;
sleep(1);
}
}
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <sys/stat.h>
#include <stdlib.h>
#define debug 0
class MyTail
{
private:
std::list<std::string> mLastNLine;
const int mNoOfLines;
std::ifstream mIn;
public:
explicit MyTail(int pNoOfLines):mNoOfLines(pNoOfLines) {}
const int getNoOfLines() {return mNoOfLines; }
void getLastNLines();
void printLastNLines();
void tailF(const char* filename);
};
void MyTail::getLastNLines()
{
if (debug) std::cout << "In: getLastNLines()" << std::endl;
mIn.seekg(-1,std::ios::end);
int pos=mIn.tellg();
int count = 1;
//Get file pointer to point to bottom up mNoOfLines.
for(int i=0;i<pos;i++)
{
if (mIn.get() == '\n')
if (count++ > mNoOfLines)
break;
mIn.seekg(-2,std::ios::cur);
}
//Start copying bottom mNoOfLines string into list to avoid I/O calls to print lines
std::string line;
while(getline(mIn,line)) {
int data_Size = mLastNLine.size();
if(data_Size >= mNoOfLines) {
mLastNLine.pop_front();
}
mLastNLine.push_back(line);
}
if (debug) std::cout << "Out: getLastNLines()" << std::endl;
}
void MyTail::printLastNLines()
{
for (std::list<std::string>::iterator i = mLastNLine.begin(); i != mLastNLine.end(); ++i)
std::cout << *i << std::endl;
}
void MyTail::tailF(const char* filename)
{
if (debug) std::cout << "In: TailF()" << std::endl;
int date = 0;
while (true) {
struct stat st;
stat (filename, &st);
int newdate = st.st_mtime;
if (newdate != date){
system("#cls||clear");
std::cout << "Print last " << getNoOfLines() << " Lines: \n";
mIn.open(filename);
date = newdate;
getLastNLines();
mIn.close();
printLastNLines();
}
}
if (debug) std::cout << "Out: TailF()" << std::endl;
}
int main(int argc, char **argv)
{
if(argc==1) {
std::cout << "No Extra Command Line Argument Passed Other Than Program Name\n";
return 0;
}
if(argc>=2) {
MyTail t1(10);
t1.tailF(argv[1]);
}
return 0;
}
I'm compiling this code with GNU GCC Compiler in Code Blocks but for some reason the log file that it creates remains empty no matter what. Any ideas why this might be?
#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
using namespace std;
int i;
string s;
int main()
{
ofstream log;
log.open("log.txt");
while (!GetAsyncKeyState(VK_F8)) {
for (i=65; i<90; i++) {
if (GetAsyncKeyState(i)) {
s+=i;
}
Sleep(10);
}
if (GetAsyncKeyState(VK_SPACE)) {
s+=" ";
}
}
log << s;
log.close();
cin.get();
}
Consider following points:
Are you trying log << "TEST" in the condition?
Try this (right after the log.open call):
log.open("log.txt");
log << "TEST" << endl;
If TEST gets written to the file, your file is empty because the condition never gets true.
An other issue might be that the file contains non-displayable characters.
Dump your file to a hex-editor. Does the file have a size of 0 or is it containing data you might not be able to display on common text editors?
*EDIT: * This should do what you want:
Either write your i or " " directly to log or use a stringstream:
#include <sstream>
//...
ofstream log;
log.open("log.txt");
stringstream str;
while (!GetAsyncKeyState(VK_F8)) {
for (i=65; i<90; i++) {
if (GetAsyncKeyState(i)) {
str << i;
}
Sleep(10);
}
if (GetAsyncKeyState(VK_SPACE)) {
str << " ";
}
}
log << str.rdbuf();
log.close();
cin.get();
Try using if(GetKeyState(0x41)) instead for your if.
Most likely your are looking for log.txt in the wrong directory
#include <iostream>
#include <fstream>
using namespace std;
void foo(){
streambuf *psbuf;
ofstream filestr;
filestr.open ("test.txt");
psbuf = filestr.rdbuf();
cout.rdbuf(psbuf);
}
int main () {
foo();
cout << "This is written to the file";
return 0;
}
Does cout write to the given file?
If not, is there a way to do it without sending the variables to foo, like new?
update :
I can't use a solution that uses class or uses global so plz can some
give me solution that use new. Also passing the from main to foo
streambuf *psbuf;
ofstream filestr;
should work right?
I am trying to do this but its not working?
I pass the stream to foo so it exist in the main so it wont end when foo finish.
void foo(streambuf *psbuf){
ofstream filestr;
filestr.open ("test.txt");
psbuf = filestr.rdbuf();
cout.rdbuf(psbuf);
}
int main () {
streambuf *psbuf
foo(psbuf);
cout << "This is written to the file";
return 0;
}
I suspect that by now compiled and run your code and found that you get a segmentation fault.
You are getting this because you create and open an ofstream object within foo(), which is then destroyed (and closed) at the end of foo. When you attempt to write to the stream in main(), you attempt to access a buffer which no longer exists.
One workaround to this is to make your filestr object global. There are plenty of better ones!
Edit: Here is a better solution as suggested by #MSalters:
#include <iostream>
#include <fstream>
class scoped_cout_redirector
{
public:
scoped_cout_redirector(const std::string& filename)
:backup_(std::cout.rdbuf())
,filestr_(filename.c_str())
,sbuf_(filestr_.rdbuf())
{
std::cout.rdbuf(sbuf_);
}
~scoped_cout_redirector()
{
std::cout.rdbuf(backup_);
}
private:
scoped_cout_redirector();
scoped_cout_redirector(const scoped_cout_redirector& copy);
scoped_cout_redirector& operator =(const scoped_cout_redirector& assign);
std::streambuf* backup_;
std::ofstream filestr_;
std::streambuf* sbuf_;
};
int main()
{
{
scoped_cout_redirector file1("file1.txt");
std::cout << "This is written to the first file." << std::endl;
}
std::cout << "This is written to stdout." << std::endl;
{
scoped_cout_redirector file2("file2.txt");
std::cout << "This is written to the second file." << std::endl;
}
return 0;
}
It seems to me that your code should work but ... Why don't you try yourself ? You will see if everything is written in test.txt or not.
I want to create a small code in C++ with the same functionality as "tail-f": watch for new lines in a text file and show them in the standard output.
The idea is to have a thread that monitors the file
Is there an easy way to do it without opening and closing the file each time?
Have a look at inotify on Linux or kqueue on Mac OS.
Inotify is Linux kernel subsystem that allows you to subscribe for events on files and it will report to your application when the even happened on your file.
Just keep reading the file. If the read fails, do nothing. There's no need to repeatedly open and close it. However, you will find it much more efficient to use operating system specific features to monitor the file, should your OS provide them.
Same as in https://stackoverflow.com/a/7514051/44729 except that the code below uses getline instead of getc and doesn't skip new lines
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
static int last_position=0;
// read file untill new line
// save position
int find_new_text(ifstream &infile) {
infile.seekg(0,ios::end);
int filesize = infile.tellg();
// check if the new file started
if(filesize < last_position){
last_position=0;
}
// read file from last position untill new line is found
for(int n=last_position;n<filesize;n++) {
infile.seekg( last_position,ios::beg);
char test[256];
infile.getline(test, 256);
last_position = infile.tellg();
cout << "Char: " << test <<"Last position " << last_position<< endl;
// end of file
if(filesize == last_position){
return filesize;
}
}
return 0;
}
int main() {
for(;;) {
std::ifstream infile("filename");
int current_position = find_new_text(infile);
sleep(1);
}
}
I read this in one of Perl manuals, but it is easily translated into standard C, which, in turn, can be translated to istreams.
seek FILEHANDLE,POSITION,WHENCE
Sets FILEHANDLE's position, just like the "fseek" call of
"stdio".
<...>
A WHENCE of 1 ("SEEK_CUR") is useful for not moving the file
position:
seek(TEST,0,1);
This is also useful for applications emulating "tail -f". Once
you hit EOF on your read, and then sleep for a while, you might
have to stick in a seek() to reset things. The "seek" doesn't
change the current position, but it does clear the end-of-file
condition on the handle, so that the next "<FILE>" makes Perl
try again to read something. We hope.
As far as I remember, fseek is called iostream::seekg. So you should basically do the same: seek to the end of the file, then sleep and seek again with ios_base::cur flag to update end-of-file and read some more data.
Instead of sleeping, you may use inotify, as suggested in the other answer, to sleep (block while reading from an emulated file, actually) exactly until the file is updated/closed. But that's Linux-specific, and is not standard C++.
I needed to implement this too, I just wrote a quick hack in standard C++. The hack searches for the last 0x0A (linefeed character) in a file and outputs all data following that linefeed when the last linefeed value becomes a larger value. The code is here:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int find_last_linefeed(ifstream &infile) {
infile.seekg(0,ios::end);
int filesize = infile.tellg();
for(int n=1;n<filesize;n++) {
infile.seekg(filesize-n-1,ios::beg);
char c;
infile.get(c);
if(c == 0x0A) return infile.tellg();
}
}
int main() {
int last_position=-1;
for(;;) {
ifstream infile("testfile");
int position = find_last_linefeed(infile);
if(position > last_position) {
infile.seekg(position,ios::beg);
string in;
infile >> in;
cout << in << endl;
}
last_position=position;
sleep(1);
}
}
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <sys/stat.h>
#include <stdlib.h>
#define debug 0
class MyTail
{
private:
std::list<std::string> mLastNLine;
const int mNoOfLines;
std::ifstream mIn;
public:
explicit MyTail(int pNoOfLines):mNoOfLines(pNoOfLines) {}
const int getNoOfLines() {return mNoOfLines; }
void getLastNLines();
void printLastNLines();
void tailF(const char* filename);
};
void MyTail::getLastNLines()
{
if (debug) std::cout << "In: getLastNLines()" << std::endl;
mIn.seekg(-1,std::ios::end);
int pos=mIn.tellg();
int count = 1;
//Get file pointer to point to bottom up mNoOfLines.
for(int i=0;i<pos;i++)
{
if (mIn.get() == '\n')
if (count++ > mNoOfLines)
break;
mIn.seekg(-2,std::ios::cur);
}
//Start copying bottom mNoOfLines string into list to avoid I/O calls to print lines
std::string line;
while(getline(mIn,line)) {
int data_Size = mLastNLine.size();
if(data_Size >= mNoOfLines) {
mLastNLine.pop_front();
}
mLastNLine.push_back(line);
}
if (debug) std::cout << "Out: getLastNLines()" << std::endl;
}
void MyTail::printLastNLines()
{
for (std::list<std::string>::iterator i = mLastNLine.begin(); i != mLastNLine.end(); ++i)
std::cout << *i << std::endl;
}
void MyTail::tailF(const char* filename)
{
if (debug) std::cout << "In: TailF()" << std::endl;
int date = 0;
while (true) {
struct stat st;
stat (filename, &st);
int newdate = st.st_mtime;
if (newdate != date){
system("#cls||clear");
std::cout << "Print last " << getNoOfLines() << " Lines: \n";
mIn.open(filename);
date = newdate;
getLastNLines();
mIn.close();
printLastNLines();
}
}
if (debug) std::cout << "Out: TailF()" << std::endl;
}
int main(int argc, char **argv)
{
if(argc==1) {
std::cout << "No Extra Command Line Argument Passed Other Than Program Name\n";
return 0;
}
if(argc>=2) {
MyTail t1(10);
t1.tailF(argv[1]);
}
return 0;
}