Hi I am trying to make a directory in windows with this code
header
#include <direct.h>
script
int main() {
string local = "C:/Program Files (x86)/Mail";
try
{
_mkdir (local.c_str ());
cout << "It is made?";
}
catch(invalid_argument& e)
{
cout << e.what () << " " << (char*) EEXIST;
if (e.what () == (char*) EEXIST) {
cout << e.what () << " " << (char*) EEXIST;
}
return;
}
}
The file is clearly not made, but it is also not making the error it should.
_mkdir won't throw an exception. (This is not python or boost, or any smart middleware)
Read the documentation you were referring to: it returns a value. 0 is OK, -1: error, ask why to errno
Don't ignore the return value. You probably have insufficient rights without UAC elevation to create the directory.
So I finally figured errno out, which for errno you need the <errno.h> header. The complete list of errno codes.
If you want to see what errno code something is throwing lets say
if (
_mkdir(((string)"C:/Program Files (x86)/Mail").c_str()) == 0 ||
errno == 17 /* this is the code for - File exists - */
){
// Do stuff
} else {
int errorCode = errno; // You need to save the code before anything else,
// because something else might change its value
cout << errorCode;
}
Related
We have written some functions in golang and a c wrapper on top of that to invoke those functions. We first build golang code to create an archive file and then we build the wrapper code in c to be consumed as a DLL.
After loading this DLL using LoadLibraryA(path_to_dll) in my program I am seeing that the inherit flags for fd 0, 1, and 2 are getting changed from 1 to 0. This does not happen immediately after loading the DLL though. I had added sleep in my code after the load library call and seems like it takes a few milliseconds after loading the library to change the flag values.
I am using GetHandleInformation((HANDLE) sock, &flags) to get the inherit flag value.
Any idea/pointers on what could be causing this? Thanks!
Updates:
I was able to find out the exact line in the go code that is flipping the inherit flag values. The global variable reqHandler in below k8sService.go code is causing this. Any idea why the use of this global variable is flipping the inherit flag values?
my-lib/k8sService.go (go code)
package main
import "C"
import (
"my-lib/pkg/cmd"
)
func main() {
}
var reqHandler []*cmd.K8sRequest
my-lib/pkg/cmd/execute.go
import (
"my-lib/pkg/dto"
)
type K8sRequest struct {
K8sDetails dto.K8sDetails
}
my-lib/pkg/dto/structs.go
package dto
// K8sDetails contains all the necessary information about talking to the cluster. Below struct has few more variables.
type K8sDetails struct {
// HostName of the cluster's API server
HostName string `json:"hostname"`
// Port on which the API server listens on to
Port int `json:"port"`
}
We have a C wrapper on top of the above k8sService.go. We first build golang code to create an archive file and then with this archive file and wrapper code in C we build the target DLL. Below is the sample program which loads this DLL and also prints the inherit flag values before and after loading the DLL.
#include <windows.h>
#include <iostream>
#include <io.h>
#include "wrapper/cWrapper.h"
void printInheritVals() {
typedef SOCKET my_socket_t;
my_socket_t fd0 = _get_osfhandle(0);
my_socket_t fd1 = _get_osfhandle(1);
my_socket_t fd2 = _get_osfhandle(2);
std::cout << "fd0: " << fd0 << std::endl;
std::cout << "fd1: " << fd1 << std::endl;
std::cout << "fd2: " << fd2 << std::endl;
DWORD flags;
int inherit_flag_0 = -1;
int inherit_flag_1 = -1;
int inherit_flag_2 = -1;
if (!GetHandleInformation((HANDLE) fd0, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_0 = (flags & HANDLE_FLAG_INHERIT);
}
if (!GetHandleInformation((HANDLE) fd1, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_1 = (flags & HANDLE_FLAG_INHERIT);
}
if (!GetHandleInformation((HANDLE) fd2, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_2 = (flags & HANDLE_FLAG_INHERIT);
}
std::cout << "inherit_flag_0: " << inherit_flag_0 << std::endl;
std::cout << "inherit_flag_1: " << inherit_flag_1 << std::endl;
std::cout << "inherit_flag_2: " << inherit_flag_2 << std::endl;
}
int main()
{
printInheritVals(); // In output all flag values are 1
HINSTANCE hGetProcIDDLL = LoadLibraryA(PATH_TO_DLL);
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Library loaded" << std::endl;
printInheritVals(); // In output all flag values are 1
Sleep(1000);
printInheritVals(); // In output all flag values are 0
return EXIT_SUCCESS;
}
This is a bug in the golang.org/x/sys/windows package. The same issue used to be in the built-in syscall package as well, but it was fixed in Go 1.17.
Something in your project must be importing the golang.org/x version of the package instead of the built-in one, and so the following code executes to initialize the Stdin, Stdout, and Stderr variables:
var (
Stdin = getStdHandle(STD_INPUT_HANDLE)
Stdout = getStdHandle(STD_OUTPUT_HANDLE)
Stderr = getStdHandle(STD_ERROR_HANDLE)
)
func getStdHandle(stdhandle uint32) (fd Handle) {
r, _ := GetStdHandle(stdhandle)
CloseOnExec(r)
return r
}
The fix for that code would be to remove the CloseOnExec call, which is what clears HANDLE_FLAG_INHERIT on the given file handle.
How to solve that in your project is less clear. I think you can vendor golang.org/x/sys module in your project, perhaps with a replace directive in your go.mod. Apply the fix in your local copy.
Meanwhile, I encourage you to also report the bug. The documentation instructs you to report the issue on the main Go project at GitHub, prefixing the title with x/sys.
I am stuck in a tight spot and I need some help with some C++ code. This is my first attempt at doing C++ and it born mostly from necessity at this point.
I am trying (unsuccessfully it feels) to build a native NAN module for Node.JS that will be used by an Electron app on Windows.
I need it to return the WinHttpDetectAutoProxyConfigUrl when the users Proxy configuration is set to Auto Detect.
I have built this exact thing in C# for another application and it works seamlessly in our distributed user BYOD environment. However in this case I do not wish to be dependent on the dot.net framework unnecessarily.
Right know I am at the extent of my knowledge when it comes to C++ as most of my knowledge over the years has thus far been theoretical. I am hoping that someone that actually works in C++ daily can look at my code and help correct the error that is happening.
I have been trying to debug using the “std::cout” in VSCode.
As you can see from the output at the bottom of the image, that some of it appears to be working and the code is dropping into the “Get Auto URL” IF block as expected. However the output is very iritic (“�����”) and nothing like the wpad.dat URL I was expecting to see returned from the wpad protocol implemented by the winhttp.dll.
My Problem:
It is as though the result is blank and then the “char buffer[2083];” is being sent to the stdOut and the characters are all encoded wrong.
Any help on this would be very helpful so thanks in advance.
Please see the code below.
main.cpp
#include <nan.h>
#include <Windows.h>
#include <Winhttp.h>
#include <iostream>
#pragma comment(lib, "winhttp.lib")
using namespace std;
// NAN_METHOD is a Nan macro enabling convenient way of creating native node functions.
// It takes a method's name as a param. By C++ convention, I used the Capital cased name.
NAN_METHOD(AutoProxyConfigUrl) {
cout << "AutoProxyConfigUrl" << "\n";
v8::Isolate* isolate = info.GetIsolate(); // args.GetIsolate();
LPWSTR strConfigUrl = NULL;
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG MyProxyConfig;
if(!WinHttpGetIEProxyConfigForCurrentUser(&MyProxyConfig))
{
//check the error DWORD Err = GetLastError();
DWORD Err = GetLastError();
cout << "WinHttpGetIEProxyConfigForCurrentUser failed with the following error number: " << Err << "\n";
switch (Err)
{
case ERROR_FILE_NOT_FOUND:
cout << "The error is ERROR_FILE_NOT_FOUND" << "\n";
break;
case ERROR_WINHTTP_INTERNAL_ERROR:
cout << "ERROR_WINHTTP_INTERNAL_ERROR" << "\n";
break;
case ERROR_NOT_ENOUGH_MEMORY:
cout << "ERROR_NOT_ENOUGH_MEMORY" << "\n";
break;
default:
cout << "Look up error in header file." << "\n";
break;
}//end switch
//TODO this might not be a good idea but it is worth trying
strConfigUrl = L"http://wpad/wpad.dat"; //Default to Fallback wpad
}//end if
else
{
//no error so check the proxy settings and free any strings
cout << "Auto Detect is: " << MyProxyConfig.fAutoDetect << "\n";
if(MyProxyConfig.fAutoDetect){
cout << "Get Auto URL" << "\n";
if (!WinHttpDetectAutoProxyConfigUrl(WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A, &strConfigUrl))
{
cout << "Error getting URL" << "\n";
//This error message is not necessarily a problem and can be ignored if you are using direct connection. you get this error if you are having direct connection.
//check the error DWORD Err = GetLastError();
DWORD Err = GetLastError();
if (ERROR_WINHTTP_AUTODETECTION_FAILED == Err)
{
strConfigUrl = L"http://wpad/wpad.dat"; //Default to Fallback wpad
}
//TODO work out what to do with the other errors
}
}
if(NULL != MyProxyConfig.lpszAutoConfigUrl)
{
wcout << "AutoConfigURL (MyProxyConfig.lpszAutoConfigUrl) is: " << MyProxyConfig.lpszAutoConfigUrl << "\n";
GlobalFree(MyProxyConfig.lpszAutoConfigUrl);
}
if(NULL != MyProxyConfig.lpszProxy)
{
wcout << "AutoConfigURL (MyProxyConfig.lpszProxy) is: " << MyProxyConfig.lpszProxy << "\n";
GlobalFree(MyProxyConfig.lpszProxy);
}
if(NULL != MyProxyConfig.lpszProxyBypass)
{
wcout << "AutoConfigURL is: " << MyProxyConfig.lpszProxyBypass << "\n";
GlobalFree(MyProxyConfig.lpszProxyBypass);
}
}//end else
//cout << "strConfigUrl" << strConfigUrl << "\n";
char buffer[2083];
wcstombs( buffer, strConfigUrl, wcslen(strConfigUrl) ); // Need wcslen to compute the length of the string
// convert it to string
std::string returnUrl(buffer);
// Create an instance of V8's String type
auto message = Nan::New(returnUrl).ToLocalChecked();
// 'info' is a macro's "implicit" parameter - it's a bridge object between C++ and JavaScript runtimes
// You would use info to both extract the parameters passed to a function as well as set the return value.
info.GetReturnValue().Set(message);
if(strConfigUrl)
GlobalFree(strConfigUrl);
}
// Module initialization logic
NAN_MODULE_INIT(Initialize) {
// Export the `Hello` function (equivalent to `export function Hello (...)` in JS)
NAN_EXPORT(target, AutoProxyConfigUrl);
}
// Create the module called "addon" and initialize it with `Initialize` function (created with NAN_MODULE_INIT macro)
NODE_MODULE(proxyautodetect, Initialize);
main.js
// note that the compiled addon is placed under following path
//const {AutoProxyConfigUrl} = require('./build/Release/proxyautodetect.node');
const {AutoProxyConfigUrl} = require('./build/Debug/proxyautodetect.node');
// `Hello` function returns a string, so we have to console.log it!
console.log(AutoProxyConfigUrl());
Build and Run output:
C:\Code\Work\wpad-auto-detect>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild --debug ) else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild --debug )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
main.cpp
win_delay_load_hook.cc
Creating library C:\Code\Work\wpad-auto-detect\build\Debug\proxyautodetect.lib and object C:\Code\Work\wpad-auto-detect\build\Debug\proxyautodet
ect.exp
proxyautodetect.vcxproj -> C:\Code\Work\wpad-auto-detect\build\Debug\\proxyautodetect.node
PS C:\Code\Work\wpad-auto-detect> npm start
> proxyautodetect#1.0.0 start C:\Code\Work\wpad-auto-detect
> node main.js
AutoProxyConfigUrl
Auto Detect is: 1
Get Auto URL
"
"��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������1��J╗
PS C:\Code\Work\wpad-auto-detect>
Image of code output
I did a sort of Trim
int urlLen = wcslen(strConfigUrl) ;
#if DEBUG
cout << "strConfigUrl wcslen : " << urlLen << "\n";
#endif
char buffer[2083]; //This is the max length a URL can be in IE
wcstombs( buffer, strConfigUrl, wcslen(strConfigUrl) ); // Need wcslen to compute the length of the string
// convert it to string
std::string returnUrl(buffer);
// Create an instance of V8's String type and Return only the Length needed so kind of Trim the extra char
auto message = Nan::New(returnUrl.substr(0, urlLen)).ToLocalChecked();
My program invokes methods that will set errno when a failure occurs, I throw errno like an exception and catch it:
try
{
if (-1 == truncate("/foo/bar.txt", 0))
{
throw errno;
}
}
catch (const int errno)
{
//log
}
Here I don't want to discuss the exception handling best practice topic. The truth is in the code above, catch block will not hit when the variable name in catch bracket is errno. This issue can be simplified to:
try
{
throw 1999;
}
catch (const int errno) //renaming "errno" to "e" works!!!
{
//unreachable code here
}
I know errno is a "special" name, but I thought C++ could handle same variable names defined in different scopes correctly.
//test.h
int my_number = 99;
//test.cpp
#include "test.h"
int main()
{
try
{
throw 1999;
}
catch(int my_number)
{
std::cout << "in catch: " << my_number << std::endl; //prints 1999
}
std::cout << my_number << std::endl; //prints 99
}
The program is compiled in GNU5.4(happens in both C++11 and C++14). Can anyone explain the strange behavior?
errno is a macro. So your exception handler contains some expanded tokens that most likely make very little sense. From the standard ([errno]):
The contents of the header are the same as the POSIX header
, except that errno shall be defined as a macro.
i made a function that first reads the file and checks if it exists or not and then it removes it after a confirmation but if i do directly like
remove("a.text");
it deletes the file that has the name a.txt but when i use my function
int deletediary()
{
string searchfilename;
cout<<"\nPlease enter the filename to be searched\n";
cin>>searchfilename;
searchfilename.append(".txt");
fileread.open(searchfilename.c_str());
if(!fileread){
cout<<"\nERROR :Either you didn't enter an invalid date or you entered an date with no entry\n\n";
A :
cout<<"Continue to search? (y/n)\n";
if(getch()=='y')
{
modifydiary();
}
else if(getch()=='n')
{
menuview();
}
else
{
cout<<"Enter Correct Option\n";
goto A;
}
}
else{
system("cls");
int i;
B :
cout<<"Are you sure you want to remove this diary entry? (y/n)";
if(getch()=='y')
{
remove(searchfilename.c_str());
}
else if(getch()=='n')
{
menuview();
}
else
{
cout<<"Enter Correct Option\n";
goto B;
}
cout<<"INFO :Deleted!!!";
system("pause");
menuview();
}
it only checks the filename but does not delete it.
In c++17 we have the filesystem library, which gives the tools to easily deal with the problem.
Example:
#include <filesystem>
#include <iostream>
#include <string>
int main()
{
std::string searchfilename;
std::cout << "Please enter the filename to be searched\n";
std::cin >> searchfilename;
try {
if (std::filesystem::remove(searchfilename))
std::cout << "file " << searchfilename << " deleted.\n";
else
std::cout << "file " << searchfilename << " not found.\n";
}
catch(const std::filesystem::filesystem_error& err) {
std::cout << "filesystem error: " << err.what() << '\n';
}
}
You forgot closing the file that you have opened.
So, CLOSE the file and it should work.
Note: The solution worked for #AkhileshSharma and included the comment as an answer to close the question as answered.
When you try to delete a file, you should always handle the return value of remove function immediately. For successful result it returns 0 and for failed, it returns non-zero.
const int result = remove( "no-file" );
if( result == 0 ){
printf( "success\n" );
} else {
printf( "%s\n", strerror( errno ) ); // No such file or directory
}
remove is in the stdio.h file
and strerror is in the string.h
So after your remove function, check to see for what reason it has not been deleted.
The error number is stored in errno variable and strerror can map the error number to a string that tells the reason of failure.
Also you can test the error code and a Linux Terminal if you have it using perror command
> perror 0
OS error code 0: Success
> perror 1
OS error code 1: Operation not permitted
> perror 2
OS error code 2: No such file or directory
> perror 3
OS error code 3: No such process
> perror 4
OS error code 4: Interrupted system call
> perror 5
OS error code 5: Input/output error
//you have to give the path of the file for example(path="C:\\data\\newfolder")
System::IO::DirectoryInfo^ directory = gcnew System::IO::DirectoryInfo(path);
for each(System::IO::FileInfo^ file in directory->GetFiles())
{
//for getting the extension of file(if you want to delete specific extension file)
String^ s = file->Extension;
if (file->Extension == ".png")
{
file->Delete();
}
}
Here is what I have so far
socklen_t cli_size;
struct sockaddr cli;
int in_sock;
/* event from TCP server socket, new connection */
cli_size = sizeof(cli);
try {
if ((in_sock = ::accept(handle,&cli, &cli_size)) < 0) {
throw in_sock;
return NULL;
}
}
catch(int ex) {
cout << "Exception Nr. " << ex << endl;
}
from man page:
On error, -1 is returned, and errno is set appropriately.
Question: I still can't understand where is errno? I need to understand exception
errno is a global integer variable that contains error codes after system calls like accept fails. You might have to include the header file <errno.h> for the variable to be defined.
In your case, you shouldn't throw the value returned by accept but the value of errno:
try
{
if ((in_sock = accept(...)) == -1)
throw errno;
// ...
}
catch (int error)
{
std::cout << "Error code " << error << " (" << std::strerror(error) << ")\n";
}
The function std::strerror is declared in the header file <cstring> and returns a string describing the error.
An important note: The value of errno is only valid if a function returns that it failed. If, in your example, accept succeeds then the value of errno is undefined.