C++ Stream class failed to open the file - c++

I write small test application in C++ to read the file data, So when I used the C++ -Stream class to read from files, it fails to open the file stream for the file name which gets passed as argument of the Stream class object.
Also I keep my file(Test.txt) in the directory where my program executable is kept and run.
#include<fstream>
#include<string>
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream testFile("Test.txt");
string line;
if (testFile.is_open())
{
while (getline(testFile, line))
{
line += line;
}
}
}
please also find the additional debug capture which has been captured from visual studio debugger.

If you run a program from the editor/IDE it is not always true (and generally it isn't) that the root directory for relative paths is the project directory or the one where the .exe is placed. If you run the executable from the command line placed in the directory it should work, but if you run it when the command line isn't in the directory you'll see the same error.
If you want the root directory to be the project one there is certainly an option in the editor/IDE, just surf the web or look into settings (probably run configurations)

The answer is: The file could not be opened. It is mispelled, or not existing.
But most likely it is in a different directory.
Please use a full path for the file, then you can open it. Like
ifstream testFile("c:\\temp\\Test.txt");
Then, please do not use is_open.
Simply use
if (testFile)
The ! operator for ifstream is overwritten, so this will work.

thanks all and I manage to get it working with the platform independent method. Please see the code below.
#include<fstream>
#include<string>
#include<stdlib.h>
#include<iostream>
#include <errno.h>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main(int argc, char *argv[])
{
fs::path Path = fs::current_path() / argv[1];
ifstream testFile(Path.c_str());
string line;
string str;
if (testFile.is_open())
{
for (std::string line; std::getline(testFile, line);)
{
str += line;
}
}
std::cout << str << endl;
}

Related

I can't read from a file

I wrote a code to make "text1.txt" file. It worked correctly, then I've been trying to read from the file, but every time is_open() function doesn't return true. Even so I copied other codes in the way exactly they are in different compilers, but it never works. How will I solve this:(
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file1("text1.txt");
string str;
if(file1.is_open()){
while(getline( file1, str)){
cout<<str;
}
}
else
cout<<"the file is not open"<<endl;
return 0;
}
How are you running your program?
The most common cause of this I've seen is that you're running your program inside an IDE (like Visual Studio), and your current directory isn't where you think it is.
Try putting in the full path to the file and see if your problem disappears.

system call not opening .jar

I am trying to open a .jar file, which is located at C:\Users\MyUser\ThisProgram.jar. I want to open it directly, using a system call, instead of having to use terminal manually. My current code is as follows:
#include <cstdlib>
#include <string>
using namespace std;
int main() {
string str2 = "java -jar C:\\Users\\MyUser\\MyProgram.jar";
const char* cmd2 = str2.c_str();
system(cmd2);
}
I am getting an error that says "Unable to access jar file ThisProgram.jar". What can I do to fix this?

why SDL_RWFromFile( file ,"w+") does not read and write like its supposed to? it only opens file for writing

can someone explain to me why this code won't work as expected. It seems SDL_RWFromFile using the w+ mode only works for writing and Not READING AND WRITING as its supposed to... what am i doing wrong
i dont want to have a different handler for reading and a different one for writing
#include <iostream>
#include <SDL.h>
using namespace std;
int main(int argc,char* args[])
{
SDL_Init(SDL_INIT_VIDEO);
int scores=2;
SDL_RWops* rwScore=SDL_RWFromFile("highscore.dat","w+");
SDL_RWwrite(rwScore,&scores,sizeof(int),1);
int fromfile=0;
SDL_RWread(rwScore,&fromfile,sizeof(int),1);
cout<<fromfile<<endl;
return 0;
}
this prints out 0;
Your problem is in "w+" that means:
write/update: Create an empty file and open it for update (both for
input and output). If a file with the same name already exists its
contents are discarded and the file is treated as a new empty file
See the description of all flags here:
https://wiki.libsdl.org/SDL_RWFromFile

A running executable that modifies itself

I have a Visual Studio 2008 C++ project for Windows CE 5 where I would like the currently running executable to modify itself.
Specifically, I would like to be able to read/write some data stored within the exe file itself. I do not need (or wish to) modify executable code.
In regular windows, I could use a string resource and the UpdateResource function, but that doesn't exist in WinCE.
CreateFile, unfortunately, fails because the file is already in use.
Does anybody have any other suggestions?
First, why do you need to do this? You should be able to do this with other methods.
I'm not particularly familiar with Windows-CE, but if you need to, you can probably copy the file, edit the copy, delete the first, and then run the other. That's an inefficient way, but if you only need to do it once or twice in the span of the program and speed isn't a concern, I guess you could do it:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]) {
// Check if this IS the copy:
if (argv[0].find(argv[1]) != string::npos) {
system("taskkill -IM myOLDfile.exe"); // Stop the old one running,
system("del myOLDfile.exe"); // Then delete it.
}
ifstream myself(argv[0]); // argv[0] is the program itself
string fullcode;
string line;
if (file.is_open()) {
while (file.good()) {
getline(myself, line);
line.append("\n");
fullcode.append(line);
}
}
myself.close();
// Do whatever you need to do to the code here.
ofstream newcode("myNEWfile.exe");
newcode.write(fullcode);
newcode.close();
system("myNEWfile.exe myNEWfile.exe"); // Starts new file. Also, not a typo.
}
Good luck on your project!

Strange fstream problem

I have really strange problem. In Visual C++ express, I have very simple code, just:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?ยจ
EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.
Canonical code to write to a file:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file;
file.open("test.txt");
if ( ! file.is_open() ) {
cerr << "open error\n";
}
if ( ! ( file << "Hello" ) ) {
cerr << "write error\n";
}
file.close();
}
Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.
As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.
Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).
fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.
Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.
Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios_base::out);
if (not file.is_open())
{
// Your error-handling code here
}
file << "Hello";
file.close();
}
You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.
Theres two ways to fix this. Either do:
file.open("test.txt", ios::out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create an ofstream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}