Ifstream.open() fails after a couple iterations - c++

I'm new the Ubuntu enviornment and I've also never used eclipse before.
So I'm trying to do a very simple task of just opening a file to read. I developed this on my mac in xcode and it works but when I put it through eclipse it fails.
I am calling this function continuously in order to simulate a state change like if someone pressed a button. The code is:
int event = 0;
ifstream inFile;
inFile.open("StatusFiles/currentEvent.txt"); //Crashes here after a couple times
if(inFile)
{
inFile >> event;
inFile.close();
}
else
{
cout << "StatusFiles/currentEvent.txt Not Found" << endl;
}
Very simple and the code is very common in order to open files in C++. There isn't a permission issues and I've included all the libraries I needed and I have the correct path.
I can read from the file a few times, but after two or three reads when i call this function, the code fails
The line it fails on line #2 is when I try to open the file. Eclipse yells at me saying:
No source available for "std::basic_ifstream>::open() at 0xb8f83982
This literally makes no sense to me and I would very much like some help!
--
Thanks

Related

GDB Skips While Loop Condition When Used With File Input

Alright Stack Overflow, I am running into a decently persistent problem in my C++ code. I'm sure this is one of those dumb mistake moments, but I have tried everything and cannot seem to squish this bug.
I have a bit of code here, and it's behavior is very odd. I have a main function that opens a file containing text I want to read in. I was taught in programming fundamentals class at my university that I could use getline() as a condition for the while loop, which is nice since it automatically terminates when it reaches the end of the file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream input_mem_traces("gcc.txt");
string trace_to_parse = "";
while(getline(input_mem_traces, trace_to_parse))
{
cout << trace_to_parse << endl;
}
}
When I compile and run it, it works just fine. It reads out every single line of the file I pass it, and returns with no problems.
However, when I try to use gdb, and set a breakpoint at the line
cout << trace_to_parse << endl;
it didn't hit the breakpoint. Curious as to why that was, I broke above the loop, and tried single stepping through the code. When I got to the while loop, and tried to step, it simply skipped to the line after it, which happened to be the end of the program.
This behavior occurs both using the VSCode GUI front end for gdb, as well as straight gdb from the command line. I am running this on Windows using Ubuntu under WSL2, and VSCode as my IDE with the Remote - WSL extension enabled.
Turns out there was some weirdness going on with the working directory with GDB. For some reason, my working directory was changing under the VSCode GUI, thus the file was not able to be opened, and the while loop condition performed as expected for that circumstance by not entering the loop. Upon the recommendation by Retired Ninja in the comments, I used an absolute path in the fstream object constructor, and that solved the issue.

getline unreliable on macOS?

as a school project I have to code a video game with SDL2, imgui and SFML and I'm facing a really weird problem :
getline seems unreliable on macOS but not on linux
Let me explain, when I compile and run my code, I am able to read my configuration file properly and display the data on screen : it is working everytime on my linux computer but on my macbook it is working like 1 time out of 5.
My configuration file :configuration file
how the information is supposed to be displayed (working properly on linux but not everytime on macOS) : how it is when it works
The code :
// Récupération des derniers paramètres
std::ifstream fichierSauvegardeR ("data/save.txt");
if (fichierSauvegardeR.is_open())
{
getline(fichierSauvegardeR, strNbDes);
strcpy(buf_nb_des, strNbDes.c_str());
getline(fichierSauvegardeR, strNbJoueurs);
strcpy(buf_nb_joueurs, strNbJoueurs.c_str());
// getline(fichierSauvegardeR, strNomJoueur);
// strcpy(noms_joueurs[0], strNomJoueur.c_str());
for (int i = 0; i < nbJoueurs; i++) {
if(!getline(fichierSauvegardeR, strNomJoueur))
{
break;
}
else
{
strcpy(noms_joueurs[i], strNomJoueur.c_str());
}
}
fichierSauvegardeR.close();
}
Note that, the first 2 lines of the configuration file are always properly read (even on macOS), what doesn't work is the other lines (I've tried replacing the "\n" by std::endl and it didn't changed anything)
Without responding to your answer (i don't have a mac for testing). I see that you use many C features. I recommend you to use "istringstream" to parse your file.
Something like this: https://stackoverflow.com/a/9551101/12374897

Codelite build presenting only the last row of output

Using CodeLite c++14, mingw-32. I'm fairly new and learning from a course to program in the languge, but i've encounterd a problem in the last couple of days i couldn't figure out. For some reason, the command line prompt shows only the last row of my output code. this happens in all types of code that i've done so far.
Something that might be connected is that sometimes on the first building & executing of code (after a clean) i'm getting an error:
mingw32-make.exe: *** [All] Error 2
It's just an inconvinice though, a second build is solving this problem for some reason. But it might be connected some how.
Any way here's an example for a code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
char vowels[] {'a','e','i','o','u'};
cout << "\nThe first vowel is " << vowels[0] << endl;
cout << "\nThe last vowel is " << vowels[4] << endl;
return 0;
}
The output that shows is only "The last vowel is u", it goes to basiclly any code i create.
Thanks!
So I found an answer, and this probably won't help alot of people because its pretty absurd. apperantly i had a mining virus on the computer which also made it so at startup only a CMD window would appear and I had to type 'explorer.exe' manually.
So mingw basiclly tried to tell me something was messing with my CMD every time i opened it. What a way to find out.
A fix for those who face the same (found on reddit #spiralspectra):
1.a) Open Run (windows key + r) and enter "%appdata%" without quotes and press enter.
1.b) Go to the Microsoft folder and delete the SoundMixer folder contained within (This is the mining software).
1.c) Open Run and enter "regedit.exe" without quotes.
1.d) Find the registry entry mentioned as([HKEY_CURRENT_USER\Software\Microsoft\Command Processor]) and remove it. This entry attempts to run the miner whenever a CMD is started.
2.a) Go to the winlogon registry entry in the same regedit software ([HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Winlogon])
2.b) Check the sub-key named "shell" and change its value to "explorer.exe" without the quotes. (This means when you log onto windows it will no longer attempt to run the miner and instead start up normally.)

Should C++ file read be slower than Ruby or C#?

Completely new to C++.
I'm comparing various aspects of C++, C# and Ruby to see if there's need for mirroring a library. Currently, simple read of a file (post update).
Compiling C++ and C# in VS 2017. C++ is in release(x64) mode (or at least compile then run)
The libraries more or less read a file and split the lines into three which make up the members of an object which are then stored in an array member.
For stress testing I tried a large file 380MB(7M lines) (after update) now getting similar performance with C++ and Ruby,
Purely reading the file and doing nothing else the performance is as below:
Ruby: 7s
C#: 2.5s
C++: 500+s (stopped running after awhile, something's clearly wrong)
C++(release build x64): 7.5s
The code:
#Ruby
file = File.open "test_file.txt"
while !file.eof
line = file.readline
end
//C#
StreamReader file = new StreamReader("test_file.txt");
file.Open();
while((line = file.ReadLine()) != null){
}
//C++
#include "stdafx.h"
#include "string"
#include "iostream"
#include "ctime"
#include "fstream"
int main()
{
std::ios::sync_with_stdio(false);
std::ifstream file;
file.open("c:/sandboxCPP/test_file.txt");
std::string line;
std::clock_t start;
double duration;
start = std::clock();
while (std::getline(file, line)) {
}
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
std::cout << "\nDuration: " << duration;
while (true)
{
}
return 0;
}
Edit: The following performed incredibly well. 0.03s
vector<string> lines;
string tempString = str.str();
boost::split(lines, tempString, boost::is_any_of("\n"));
start = clock();
cout << "\nCount: " << lines.size();
int count = lines.size();
string s;
for (int i = 0; i < count; i++) {
s = lines[i];
}
s = on the likelihood that I don't know what boost is doing. Changed performance.
Tested with a cout of a random record at the end of the loop.
Thanks
Based on the comments and the originally posted code (it has now been fixed [now deleted]) there was previously a coding error (i++ missing) that stopped the C++ program from outputting anything. This plus the while(true) loop in the complete code sample would present symptoms consistent with those stated in the question (i.e. user waits 500s sees no output and force terminates the program). This is because it would complete reading the file without outputting anything and enter into the deliberately added infinite loop.
The revised complete source code correctly completes (according to the comments) in ~1.6s for a 1.2 million file. My advice for improving performance would be as follows:
Make sure you are compiling in release mode (not debug mode). Given the user has specified they are using Visual Studio 2017, I would recommend viewing the official Microsoft documentation (https://msdn.microsoft.com/en-us/library/wx0123s5.aspx) for a thorough explanation.
To make it easier to diagnose problems do not add an infinite loop at the end of your program. Instead run the executable from powershell / (cmd) and confirm that it terminates correctly.
EDIT: I would also add:
For accurate timings you also need to take into account the OS disk cache. Run each benchmark multiple times to 'warm-up' the disk cache.
C++ doesn’t automatically write everything the instant you tell it to. Instead, it buffers the data so it can write it all at once, which is usually faster. To say “I really want to write this now.”, you need to say something like std::cout << std::flush (if you use std::endl to end your lines it does this automatically).
Usually you don’t need to do this; the buffers are flushed when the program exits, or when you ask for input from the user, or things like that. However, your program doesn’t exit, so it never flushes its buffer. You read the input, and then the program is executing while(true) forever, never giving the output.
The solution to this is simple: remove the while loop at the end of the program. You should not have that; people usually assume a console program exits when it’s finished. I would’ve guessed you had that because Visual Studio automatically closed the console window when the program was finished, but apparently it doesn’t do that with Ctrl+F5, which you use, so I’m not sure.

C++ , won't display last line of code

Shouldn't this work? I mean, the code is merely a test and is meant so that the dialogue goes this way : What is your name? name here, Hello name here, and yet it does not show the last line of Hello after I type in my name and click enter it just dissapears. Here is the code.
#include <iostream>
#include <string>
int main (void)
{
using std::cin;
using std::cout;
using std::string;
string name = "";
cout << "What is your name, pls?\n";
cin >> name;
cout << "\nHello " << name.c_str() << "\n";
return 0;
}
My guess is that you are running from the debugger, or double clicking the executable. In either of those cases, when the program ends, the console will close. So, the program produced output, but you just could not see it before the console closed.
Run the program from a pre-existing console so that the console remains after your program ends. Or, just whilst debugging, arrange that your program does not terminate immediately after emitting its final output. A simple way to do that is to place a break point at the end of the program.
It probably showed it right before it disappeared. If you're going to write console programs, and if you're going to send output to a console, you should run them from a console so the output has some place to go.
After you are done with your program, press Ctrl + F5 ( Run without debugging). This will prompt before closing the window and this is what you want.
Make sure you put a breakpoint before main goes out of scope. I guess your console disappears under VS?
Also, you don't need to extract the char* in the last cout statement:
cout << "\nHello " << name << endl;
Open a terminal (or a command prompt window).
Navigate to the folder that contains the executable.
Run it.
It's not disappearing. It is just running really fast.
Every IDE has a keyboard shortcut that allows you to run code and pause after the execution has finished.
This keyboard shortcut is Ctrl-F5 in Visual Studio.
I have no idea what IDE you're running, but that is your basic problem.
The other thing you can do is to test your code in ideone : ideone.com/hb4Cel (it's the same code. There is no point pasting it here)
A dirty workaround is to add something like this
cin >> name;
at the end, just before return 0;. It forces the window to wait for input (i.e. hitting return) before returning (which closes the program).
This isn't necessarily good design, but if all you want to do is run some tests then it'll do the trick.
Basically when you enter your name it displays your last line and exits after return 0.
Here are the following things to avoid that
1- use command line to run the application
Start->accessories->command prompt
Go to folder in which your application is using cd command
c:>cd c:\path\foldername
Now run the application by typing the program name e.g
c:\path\foldername>my_application.exe
It will display your last line.
2- Now if your are using microsoft visual c++ press ctrl+F5 to run your program
3- This is not recommended but you an use it as long as your are debugging then remove it from the code afterwards. Include conio.h header file and add getch(); line before return statement. It would hold the screen for you till you press a key.