Windows drag and drop problem with console app - c++

I have a program that creates a file and writes to it using ofstream. I need the program to be able to parse command line parameters later on. But for some reason, it does not create a file when I drag-and-drop a file onto the compiled executable, even if the program doesn't involve any command line parameters at all. If the executable is run normally, it works. So I'm left totally confused. Here is the source:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream outfile;
outfile.open("test.txt");
if(outfile.is_open())
{
outfile << "Test";
outfile.close();
}
else cout << "Unable to open file";
return 0;
}
Does anybody have any ideas? I appreciate any help.

You are not using the command line arguments at all. Recode your main() method to look like this:
int main(int argc, char** argv)
{
if (argc != 2)
{
cout << "Usage: blah.exe file" << endl;
return 1;
}
ofstream outfile;
outfile.open(argv[1]);
if(outfile.is_open())
{
outfile << "Test";
outfile.close();
}
else cout << "Unable to open file";
return 0;
}
Be careful what you drop, your code rewrites the file contents.

The following code does what the OP wants:
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char ** argv )
{
cout << argv[1] << endl;
ofstream outfile;
outfile.open("testzzzzzzz.txt");
if(outfile.is_open())
{
outfile << "Testzzzzz";
outfile.close();
cout << "wrote file"<< endl;
}
else cout << "Unable to open file";
string s;
getline( cin, s );
return 0;
}
It allows drag and drop, but doesn't use the dropped file name in the file open. When you drop a file in it, you get the message
"wrote file"
Unfortunately, at the moment I have no idea where it wrote the file - not in the current directory, definitely. Just going to do a search...
Edit: It creates it in your Documents and Settings directory. So to put it in the current directory, you probably need to explicitly prefix it with "./", but I havent't tested this - I leave it as an exercise for the reader :-)

Since you have not specified a path, the file, test.txt, will be saved to the default path. Just bring up a command prompt (i.e. run cmd.exe) and the command prompt will show you the default path. The file should be in this directory.
You can change the default path by editing the HOMEDRIVE & HOMEPATH environment variables.
Also, you should note the other answers. You should be using argc/argv to specify the output file.

you haven't specified a path for "test.txt" so it will try and create that file in the current working directory of the executable. This will be different when the exe is invoked by dropping a file on it than it is when you run the program normally.
Try giving "test.txt" a full path and see if that works.
edit:
To write your output file to the path that contains the exe, you would use
GetModuleFileName(NULL, ...) to the the full path of the exe,
then PathRemoveFileSpec to strip off the exe name, leaving just the exe path then
PathCombine to append test.txt to the exe path

Related

Can't open file properly in C++

I'm trying to read each line from a .geom file and save that in a string.
The user shall input the correct (absolute) filepath and then, until now, should get the content of the .geom file printed out on the console.
The problem is that under every circumstance it seems impossible to open the file via my c++ program.
Everytime I check if the file is opened via is_open() it responds with false.
The program, my IDE and the .geom file are all on the same drive and i am currently using windows. The IDE im using is Codeblocks and the executable is build in it.
This is my complete code until now:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//a function to check if the given file has the .geom extension
bool isGeom(string file){
if(file.substr(file.find_last_of(".") + 1) == "geom") {
return true;
} else {
return false;
}
}
//main func
int main()
{
string filepath, geomInput, line;
cout << "----- GeomView2obj -----" << endl;
cout << "Please enter a valid file path to a .geom file to convert it to an .obj file: \n" << endl;
//get file path by user
getline(cin, filepath);
//declare stream and open file if possible
ifstream geomFile (filepath.c_str());
if(!geomFile.is_open()){
cout << "\nERR: The given file path is invalid or the file does not exist!" << endl;
return 1;
}
if(!isGeom(filepath)){
cout << "\nERR: The given file is not a .geom file!" << endl;
return 1;
}
//read chars from geom file
while(getline(geomFile, line)){
geomInput.append(line + "\n");
}
//print string --- DELETE
cout << geomInput;
geomFile.close();
return 0;
}
I also tried to first declare my ifstream and then opening the file.
I also turned the user input off and entered an absolute path where every folder was seperated with two backslashes \\ instead of one.
I also copied the file to the folder the compiled program lies in and giving the program a relative path to the file as an input, but that also did not help.
Any form of help is much appreciated!

attempting to append text to a (fake) host file in C++ 11

I'm essentially attempting to append text to a host text file on MacOS (mojave) and it's not working.
I created a fake host file located at: /public/etc/hosts (real host file is private/etc/hosts)
and all I'd like to do in this scenaro is append the word "data" to the end of the hosts.txt file. When I run the application, it says the the file opens successfully, but the file remains unmodified after execution.
Code:
#include <iostream>
#include <fstream>
int main(int argc, const char * argv[]) {
std::ofstream myfile;
myfile.open("/public/etc/hosts.txt", std::ios::app);
if(!myfile.is_open()){
std::cout << "File could not be opened";
} else {
myfile.open ("hosts.txt", std:: ios::app);
myfile << "data";
std::cout << "Host file has been modified /n";
myfile.close();
}
return 0;
}
the above returns: Host file has been modified
here is file structure:
hosts.txt location on MacOS mojave
If I'm not mistaken the word "data" should be appended to the hosts.txt file after execution and since file.is_open checks out I'm really not sure why this isn't working.
Any insight is appreciated, thanks

Ifstream cannot open file with amdinistrator rights

I used this code to try to open and read the file (not empty), but ifstream did not work - it could not open the file: I addded the check on file opening and it showed, that ifstream even did not (could not) open the file.
I gave administrator rights to the program, but ifstream still could not read the file.
I also tried to find a path, where ifstream would read this file, but I did not success, and at last I tried to open file using the absolute path - but result is the same.
The file is situated in the root folder of the program, but I placed it everywhere and nothing changed.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string s;
ifstream file("fix.txt");
if (file)
cout << "SUCCESSFULL OPENING" << endl;
while (getline(file, s)) {
cout << s << endl;
s += "+";
cout << s << endl;
}
file.close();
return 0;
}
You may have access to a more detailed error code by activating exceptions on the stream via
file.exceptions(std::ios_base::failbit);
Then, you get more details by writing
try {
file.open("fix.txt");
}
catch(std::ios_base::failure& f) {
// f.what() contains a message, f.code() returns a std::error_code
}

File cannot be read in when using Visual Studio 2010 Debugger

So, I am using https://stackoverflow.com/a/298713/1472828 to put an argument "hands.txt" (my agrv[1], which is a file I wanna open) in my command arguments. I have tried both hands.txt and "hands.txt", neither of them worked.
int FileParsing(vector<Card> & v, char * FileName) {
ifstream ifs;
ifs.open(FileName);
if (!ifs.is_open()){
cout << "file cannot be opened." << endl;
} else {
So I use debugger to step through my main:
int main(int argc, char * argv[]){
if (argc !=2 ){
//ErrorMessage();
} else {
...
Debugger tells me that my argc is 2, which is right, but how come every time the debugger just goes to
cout << "file cannot be opened." << endl;
which means the argument just fails at reading it
ifstream ifs;
ifs.open(FileName);
Is there something I missed or I passed the argument in a wrong way?
p.s. The text file was read perfectly from cmd, so it's not the problem of code.
Got the idea from #WhozCraig, while running your program in cmd, the text file is put under debug directory. But if you run it using debugger, you have to put the text file in the same directory with other cpp and h files.

In C++, after opening a .txt file with values, reading the file gives me ""

Here's my code.
ifstream readFile;
readFile.open("voltages.txt");
if (readFile.fail( ) )
{
cout << "\nCould not open the file ... check to see if voltages.txt exists\n";
system("pause");
return;
}
string tempString = "";
//readFile.seekg(0, ios::beg);
int idx = 0;
if (readFile.is_open())
{
while ( readFile.good() )
{
getline(readFile,tempString);
cout << tempString << endl;
}
readFile.close();
}
If I move the voltages.txt to c:/, then it works fine, but I have it in the same folder as my .exe right now, and when I set a breakpoint at cout << tempString << endl; it shows up just as "". I'd like to keep it in the .exe if possible. As you can see I tried seeking to the beginning, with no luck. Please help this C++ noob! Thank you!
It might be because you are trying to read a local file when the program requires a link to the file from C:/
You can test this by replacing voltages.txt with C:/pathToVoltages/voltages.txt
I would suggest passing the file to your executable by doing this:
int main(int argc, char argv[]){
ifstream readFile;
readFile.open(argv[2]);
/*Rest of the code*/
This assumes the path to the file is given by the first argument you give to the program as in:
./program pathToFile/voltages.txt
Hope this helps