Why is cout flushing early? - c++

I've been learning how flushing works with cout, so I decided to perform this quick test.
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
cout << "Line 1..."; // OR cout << "Line 1..." << flush;
usleep(500000);
cout << "\nLine 2" << endl;
cout << "Line 3" << endl ;
return 0;
}
In the case that is presented above, the expected output is for:
Line 1...
Line 2
Line 3
to print out altogether after some delay. However, in the scenario in which
"<< flush;" is included, the expected result is for Line 1 to print immediately, then after some delay, Line 2 and Line 3 print.
These expected outputs ONLY occur when I compile my program on a Linux machine using the command:
g++ -o myFile.out myFile.cpp -Wall
Then run it using:
./myFile.out
When I run these same code pieces on my windows machine, line 1 is ALWAYS displayed immediately, regardless of the insertion of "<< flush;". Why does this happen?
It should be noted that on my windows machine, I am compiling and running my code through codeblocks x64. According to Codeblocks Settings > Compiler > Toolchain Executables, my C++ compiler is "mingw32-g++.exe". Isn't this the same compiler as running g++ on Linux as I did earlier? Thanks!

Related

Arguments passed to the command line not printed and the program loops indefinitely

I'm trying to implement a simple command line program that takes three arguments and prints them on the linux terminal
For example:
>c++ exec.cpp
>./a 32 + 32
Should print out contents like this
32
+
32
But the program is looping indefinitely
I've implemented a check for argc
Like this
if(argc!=3) {
cout << "Exit" << endl;
return -9999;
}
In case the argument count is 3
These lines of code should be executed
else {
for(int i=0;i<argc;i++){
cout << argv[i] << endl;
}
}
But as I explained before the program loops indefinitely
EDIT:
Since I was asked to post the entire code here it is
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc,char* argv[]) {
if(argc!=3) {
cout << "Exit" << endl;
return -9999;
}
else {
for(int i=0;i<argc;i++){
cout << argv[i] << endl;
}
}
}
Your code is working...
I made slight modifications (eg. argc !=4 , i <= argc , etc. )
I compiled it using gcc (g++) on my linux system using:
g++ exec.cpp -o a.out
./a.out
Output:
Exit
When I run:
./a.out 4 + 3
Output:
4
+
3
Now with code, that does look okey to me in fact.
There doesn't seem to be a way to have an endless loop in every case.
What happens if you add return(0); to the very end of the main function?
Main always has to return something and compilers normally either complain or do that on their own hwoever if the propgrammer didn't add it.
Oh, have you tried the cerr variant instead of cout for your error message? Because returning from the main right after, is quite the same as the crash I mentioned.

How to write to .txt file without recreating existing file

I have basic logging process. When an error occured in the program, it has to been logging to a .txt file. I use following code for this:
#include <fstream>
fileName = "logs/error_log.txt";
ofstream myfile;
myfile.open (fileName,fstream::app);
myfile << serialized_string << endl;
myfile.close();
When an error occured it goes to error_log.txt file successfully. But when program crashed and is restarted afterward, new logs are not logged as append. As expected the way I am using creates a new file which has same name existed file and write on it. Can someone explain me how should I write older logs as well?
Edit: These are steps I have faced:
I am using raspbian and I compile with following:
g++ main.cpp -lwiringPi -lpthread -lcurl -o test
That is the whole function.
int putLog(const char* process, int logType, string logData) {
isLoggerBusy = true;
string fileName;
std::string color;
switch (logType) {
case 0:
fileName = "logs/error_log.txt";
// color = "\033[0;31m";
break;
case 1:
fileName = "logs/info_log.txt";
// color = "\033[0;36m";
break;
case 2:
fileName = "logs/state_log.txt";
// color = "\033[1;33m";
break;
}
if (process == "WebSocket") {
color = "\033[1;32m";
}
json j = {
{"Process", process}, {"Time", currentDateTime()}, {"Log", logData}};
string serialized_string = j.dump();
fix_utf8_string(serialized_string);
ofstream myfile;
myfile.open(fileName, fstream::app);
cout << color << serialized_string << '\n';
myfile << serialized_string << endl;
myfile.close();
isLoggerBusy = false;
cout << "\033[0m" << endl;
return 0;
}
I started the program. It write downs these lines to the state_logs.txt
{"Log":"Incoming
Message{\"Action\":\"Heartbeat\",\"Data\":null}","Process":"WebSocket","Time":"2018-08-16.14:53:52"}
{"Log":"GSM Setup
Finished","Process":"SMSService","Time":"2018-08-16.14:54:13"}
Stopped the program with CTRL-C and control the state_logs.txt and I can see now two lines there.
Restart the program and interrupt with CTRC-C again in 10 seconds (before a new line logging.)
I check the state_logs.txt again and now I can not see nothing. Re-did this process but this time waiting a bit more before interrupt program(just a bit more to get only one line of log.). So now I can see only one and timestamps has been changed.
I cannot reproduce what OP describes.
I just tested on cygwin/Windows 10. (I didn't know how to make this test on an online compiler.)
testFStreamApp.cc:
#include <iostream>
#include <fstream>
int main()
{
std::cout << "Log error...\n";
{ std::ofstream log("testFStream.log", std::ios::out | std::ios::app);
log << "Error happened!" << std::endl;
}
std::cout << "Going to die...\n";
abort();
return 0; // should never be reached
}
Test Session:
$ g++ -std=c++11 -o testFStreamApp testFStreamApp.cc
$ rm testFStream.log
$ for i in 1 2 3; do
> echo "$i. start:"
> ./testFStreamApp
> done
1. start:
Log error...
Going to die...
Aborted (core dumped)
2. start:
Log error...
Going to die...
Aborted (core dumped)
3. start:
Log error...
Going to die...
Aborted (core dumped)
$ cat <testFStream.log
Error happened!
Error happened!
Error happened!
$
YSC pointed out that I made some silent changes. I did it assuming no relevance.
However, to erase any excuses, I tried also:
#include <iostream>
#include <fstream>
int main()
{
std::cout << "Log error...\n";
std::ofstream log;
log.open("testFStream.log", std::fstream::app);
log << "Error happened!" << std::endl;
log.close();
std::cout << "Going to die...\n";
abort();
return 0; // should never be reached
}
The output was exactly as above.
I hadn't dared to test this but doctorlove encouraged me:
#include <iostream>
#include <fstream>
int main()
{
std::cout << "Log error...\n";
std::ofstream log;
log.open("testFStream.log", std::fstream::app);
log << "Error happened!" << std::endl;
std::cout << "Going to die...\n";
abort();
log.close();
return 0; // should never be reached
}
Even in this case, I got the same result.
At this point, I must admit that cygwin is just a wrapper around the win32 API. So, in this case, I wouldn't wonder if this behaves different on other OSes.
I'm aware that std::endl does a flush() insight. The question is how far down (into the system) the flush() is effective. (In daily work, I try to write the code in a way that it is not necessary to rely on such details...) ;-)

Double Clicked Compiled C++ Unix Executable Doesn't Open Existing File to Read Information From

I've been searching online to solve the above issue with no
success so far. I will describe the issue in more details below.
My program contains only one .cpp file. The program should display text from "test.txt" if this file is opened. Otherwise, it should display the "Failed to open ..." message. The issue follows:
I open terminal, go to the directory containing my file, compile and run with the usual commands: "g++ main.cpp" and "./a.out". When I run my program in this way, using terminal directly, the program works correctly. It displays text when the text file exists and outputs error when it doesn't exist. When I double click the unix executable "a.out", even though the text file exists and is put side by side with the executable, the program displays "Failed to open ..." message. I don't know what to think at that point. Should code contain anything else besides what is below?
Operating system: OS X 10.9.5
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_CHAR_READ = 100;
int main(int argc, const char * argv[])
{
ifstream read_file;
cout << endl << endl;
//Allocate dynamic memory
char * file = new char[strlen("test.txt") + 1];
char * text_line = new char[MAX_CHAR_READ + 1];
strcpy(file, "test.txt");
//Attempt to open a file for reading
read_file.open(file);
if(read_file.is_open() == true)
{
cout << "File: " << file << " is open!" << endl;
read_file.get(text_line, MAX_CHAR_READ, ';');
cout << text_line << endl;
read_file.close();
}
else
cout << "Failed to open: " << file << endl;
cout << endl << endl;
//Deallocate dynamic memory
delete [] file;
delete [] text_line;
return 0;
}
Program execution example using terminal manually:
$ cd Desktop/Other/Test
$ g++ main.cpp
$ ./a.out
File: test.txt is open!
Hello World!
$
Program execution example double clicking the same executable:
$/Users/vladimirmeshcheryakov/Desktop/Other/Test/a.out ; exit;
Failed to open: test.txt
logout
[Process completed]
one of the possible things to cause it could be the case of running the terminal as superuser, in a folder with access restriction to the regular user. (superuser doesn't have that restriction)
solution: give current user the right to Read/Write in this folder.
Now I need to find a solution of obtaining the path to executable.
Check whether argv[0] contains it.

std::endl results in crash

During the development of a simple example (I haven't programmed C++ for some time) I encountered a weird behaviour. Following hello world program crashes under Windows (Mingw):
#include <iostream>
int main () {
for (int idx = 0; idx < 5; idx++) {
std::cout << "Hello World" << std::endl;
}
return 0;
}
If I remove std::endl the program does not crash though.
I use following commands to compile and execute the example, with Mingw32 (g++ 4.8.1) on a 64bit system and OS:
g++ example.cpp -o example.exe
example.exe
The error message is:
example.exe does not work any longer...
Is this a known issue or an obvious mistake of mine?
<< endl is a manipulation essentially a function. your output cant be flushed which is causing problems.

How to compile and run C++0x with GCC/G++ in Eclipse CDT?

I am trying to figure out how to use the upcoming C++ release 0x. It should be available in GCC 4.3+ with using the gcc std=gnu++0x option.
My simple thread program using 0x compiles in Eclipse CDT with std=gnu++0x added in Project > properties > C/C++ Build > Settings > Miscellaneous > Other flags.
#include <iostream>
#include <thread>
using namespace std;
void hello()
{
cout << "Hello Concurrent World!" << endl;
}
int main()
{
cout << "starting" << endl;
thread t(hello);
t.join();
cout << "ending" << endl;
return 0;
}
The program only prints "starting" and returns 0. Does anyone know why it does not run the hello function threaded?
To use threads you also need to link against the threading library.
In case you haven't done that add -lpthread to your command line or in your case to other flags field.
The command line execute (visible in your console window in eclipse) should look like this:
gcc -std=gnu++0x -lpthread <source_file_name>.cc