c++ CopyFile function problem - c++

Hey guys i need to use CopyFile in win 2000 and above platforms.
i want to copy my application to a different folder say c:.
so this works:
BOOL didThisFail = FALSE;
if (CopyFile(L"MyApplication.exe", L"something.exe", didThisFail))
cout << "File was copied" << endl;
but this dosen't:
BOOL didThisFail = FALSE;
if (CopyFile(L"MyApplication.exe", L"C:\\something.exe", didThisFail))
cout << "File was copied" << endl;

GetLastError() will tell you why it failed, probably an access denied error.

sometimes copy can fail if you can run out of disk space. When i got stuck in this problem i changed copy command to Move and it worked out for me.
I used to get error code 112.

Related

Why would fstream.fail() return true or false

I'm working through some work with some code already provided. There is an if statement that includes 2 fstream.fails(). The code is continually returning true and I'm not sure if it's because of a problem with the provided code or if I am missing something.
I've googled around to try and better understand what could be going on, but due to me being new to C++, I'm finding it hard to find an answer that helps me understand what might be going on.
The provided code where I think might be a problem.
bool Navigation::BuildNetwork(const string &fileNamePlaces, const string &fileNameLinks)
{
fstream finPlaces(fileNamePlaces);
fstream finLinks(fileNameLinks);
if (finPlaces.fail() || finLinks.fail()) return false;
ifstream();
// Add your code here
}
Where the "Build network" function is called
ACW_Wrapper wrapper("log.txt");
// Build Navigation
wrapper.startTimer();
Navigation nav;
if (nav.BuildNetwork("Places.csv", "Links.csv")) {
const auto elapsed = wrapper.stopTimer();
std::cout << std::fixed << std::setprecision(1) << "BuildNetwork - " << elapsed << " microseconds" << std::endl;
}
else {
std::cout << "\n*** Error *** BuildNetwork" << std::endl;
}
I would expect it to return false since this is provided code, but I'm unsure if I need to add something that would give me the expected outcome.
From the ios::fail documentation:
true if badbit (Read/writing error on I/O operation) and/or failbit (Logical error on i/o operation) are set.
which suggests that at least one of the two files is not opened successfully.
The problem is not in the code, the problem is with your program trying to open files that are not probably found (or it doesn't have permissions to).
Copy the files to the same workspace (folder) with your executable, and try again.

Can't get an output from my c++ application

I'm using Microsoft Visual C++ Express, and I'm wondering what's wrong with the following application, I can't get an output, it gives me an error. Since I'm not English, the error is in a different language, but it basically says something along the lines of 'The system can't find the given/stated path'.
I have literally checked it a dozen times but I can't seem to find what I'm doing wrong. Here's the code:
#include <iostream>
using namespace std;
int DemoConsoleOutput ()
{
cout << "This is a simple string literal" << endl;
cout << "Writing number five:" << 5 << endl;
cout << "Performing division 10/5 = " << 10 / 5 << endl;
cout << "Pi when approximated is 22 / 7 = " << 22 / 7 << endl;
cout << "Pi more accurately is 22 / 7 = " << 22.0 / 7 << endl;
return 0;
}
int main()
{
return DemoConsoleOutput ();
}
Can anyone help me find what's wrong with this?
Addendum: I also keep getting a weird error on my computer every couple minutes. It says: 'a program can't display a message on the desktop' and it gives me the options to show the message, or to give me another reminder in a few minutes. When I click 'show message' my screen goes black for a second and it then gives an error 'The application data folder for Microsoft visual c++ 2010 express could not be created'.
I don't know if it's important, but my OS is windows vista.
From the situation it seems that the application has insufficient rights to create a working folder and write an file in that folder. Possible causes can be that your anti virus is not letting VS do so or the folder has no write rights. Please go through this question.

what would make ios::fail() evaluate to 1?

i am trying to open a file with
27 string tline;
28 ifstream finp; // input file
29 ifstream dinp; // data files
30
31 finp.open(argv[1]);
32
33
34 cout << "finp.good() = " << finp.good() << endl;
35 cout << "finp.bad() = " << finp.bad() << endl;
36 cout << "finp.fail() = " << finp.fail() << endl;
and i end up with output
finp.good() = 0
finp.bad() = 0
finp.fail() = 1
now, i cannot find any good documentation on what would cause this other than that it is an internal logic problem. what am i supposed to do to correct this?
if it helps, i am running on linux where i need to include both <cstring> and <cstdlib> while i do not have to do this when running on OSX. could this be the problem? if so, how do i correct it?
fail() will return 1 when you attempt a conversion and it fails. For example, if the next character in the file is something other than a digit, and you attempt to read an int, then the failbit will be set, and fail() will return 1. Any conversion attempted when you're already at the end of the file will also set the failbit.
fail() will also return 1 when/if the badbit is set. This is set to signal a serious problem with the file itself, not just an inability to read some particular piece of data from the file.
forgive me, i made a simple mistake. when i ported my source files over to the linux system, i had ported over a script as well. i was confusing the executable with the script and the script had a filename hardcoded into it which was not in the directory.
basically, i was accidentally trying to read a file which was not there!

fstream::close() doesn't close file

I have a program that reads a set of files, closes them, and then attempt to delete them.
Sometimes (not always, but pretty often) the delete fails with 'sharing violation' error.
Using sysinternals process monitor I saw that in these cases the close operation wasn't reflected in the process monitor.
It appears that sometimes the close system call is skipped for no apparent reason, and without any exception.
This is happening on a windows 7 64bit machine using visual studio 2010.
Code sample;
void readFile(string file)
{
ifstream stream(file);
string line;
while(getline(stream, line))
{
cout << line << endl:
}
stream.close(); // this is redundant
}
// calling code:
readFile(file);
if(remove(file.c_str()) != 0)
{
cout << "file deletion failed" << endl;
}
Firsty your code is lacking a ;. Change this cout << line << endl: to this cout << line << endl;
Here's a similar problem : Any reason why an std::ofstream object won't close properly?
This could happen if you are creating processes in-between using CreateProcess with bInheritHandles=true. The new process will inherit the file handle and the file won't be closed by your main process as there is still an outstanding handle. This may explain why you can't see the close operation in Process Monitor, the OS will close the file once all handles have been released.

Unable to write file in C++

I'm trying to to the most basic of things .... write a file in C++, but the file is not being written. I don't get any errors either. Maybe I'm missing something obvious ... or what?
I thought there was something wrong with my code, but I also tried a sample I found on the net and still no file is created.
This is the code:
ofstream myfile;
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt");
myfile << "Writing this to a file.\n";
myfile.close();
I've also tried creating the file manually beforehand, but it's not updated at all.
I'm running Windows 7 64bit if that has got something to do with this. It's like file-write operations are completely forbidden and no error messages or exceptions are shown.
You need to open the file in write mode:
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt", ios::out);
Make sure to look at the other options for that second argument, as well. If you're writing binary data you'll need ios::binary for example.
You should also be checking the stream after opening it:
myfile.open(...
if (myfile.is_open())
...
Update:
AraK is right, I forgot that an ofstream is in write mode by default, so that's not the problem.
Perhaps you simply don't have write/create permissions to the directory? Win7 defaults a lot of directories with special permissions of "deny all". Or perhaps that file already exists and is read-only?
Start off by turning that slash around.
Even Windows understands the slash being the other way around.
ofstream myfile("C:/Users/Thorgeir/Documents/test.txt");
You could test if there are any errors:
if (!myfile)
{
std::cout << "Somthing failed while opening the file\n";
}
else
{
myfile << "Writing this to a file.\n";
myfile.close();
}
Make sure the directory exists.
If the file exists make sure it is writeable (by you)
Check the directory you are writing into is writeable (by you)
Have you read about UAC (User Account Control) and UAC Virtualization / Data Redirection in Windows Vista and 7? It's possible that your file is actually in the Virtual Store.
User Account Control Data Redirection
Your example output directory is in Users, so I wouldn't think this would be the issue, but it's a possibility worth mentioning and something that can be very frustrating if you're not looking out for it!
Hope this helps.
This code should catch any error. Most likely it's a permissions thing if any errors are encountered. Make sure you can read/write to the folder you're creating the file in.
#include "stdafx.h"
#include <fstream>
#include <iostream>
bool CheckStreamErrorBits(const std::ofstream& ofile);
int _tmain(int argc, _TCHAR* argv[]) {
std::ofstream ofile("c:\\test.txt");
if(ofile.is_open()) {
CheckStreamErrorBits(ofile);
ofile << "this is a test" << std::endl;
if(CheckStreamErrorBits(ofile)) {
std::cout << "successfully wrote file" << std::endl;
}
}else {
CheckStreamErrorBits(ofile);
std::cerr << "failed to open file" << std::endl;
}
ofile.close();
return 0;
}
//return true if stream is ok. return false if stream has error.
bool CheckStreamErrorBits(const std::ofstream& ofile) {
bool bError=false;
if(ofile.bad()) {
std::cerr << "error in file stream, the bad bit is set" << std::endl;
bError=true;
}else if(ofile.fail()) {
std::cerr << "error in file stream, the fail bit is set" << std::endl;
bError=true;
}else if(ofile.eof()) {
std::cerr << "error in file stream, the eof bit is set" << std::endl;
bError=true;
}
return !bError;
}
Update:
I just test my code under Windows 7 Enterprize and it failed the first time (fail bit was set). Then I turn off User Account Control (UAC) and tested again and it wrote the file. That is probably the same problem you're seeing. To turn off UAC go to:
Control Panel (view by Small icons) | User Accounts | Change User Account Control settings. Set it to Never notify then click OK button. You will have to restart for the changes to take affect.
I'm curious how to make it work with UAC on, i'll look into that.
Try this:
if( ! myfile)
{
cerr << "You have failed to open the file\n";
//find the error code and look up what it means.
}
Use FileMon and look for failed WriteFile calls from your process.