C file cannot be compiled in c++ Visual Studio - c++

For some reason I can no longer compile a c file in my c++ clr console application. It worked before without the clr support, I also switched my project to compile as /TP still not working. Any help would be greatly appreciated.
Error
Severity Code Description Project File Line Suppression State
Error C2664 'int strcmp(const char *,const char *)': cannot convert argument 1 from 'WCHAR [260]' to 'const char *'
snowkill.c
#include "snowkill.h"
void killProcessByName(WCHAR *filename)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes)
{
if (strcmp(pEntry.szExeFile, filename) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD)pEntry.th32ProcessID);
if (hProcess != NULL && pEntry.th32ProcessID != GetCurrentProcessId())
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
snowkill.h
#pragma once
#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
void killProcessByName(WCHAR *filename);
#ifdef __cplusplus
}
#endif
main.cpp
#include "stdafx.h"
#include "snowkill.h"
#include "motion.h"
#include "info.h"
#include "flushsound.h"
#include "snowserial.h"
using namespace System;
bool on() {
return true;
}
bool off() {
return false;
}
int main()
{
listenoncommport();
for (;;) {
string onoff = checkfile();
if (onoff == "1")
{
//detected();
}
else
{
WCHAR *proccc = L"firefox.exe";
killProcessByName(proccc);
//notdetected();
}
Sleep(5000);
}
return 0;
}

You could change every instance of WCHAR to TCHAR so text setting is "generic", or as already mentioned, change the project property character set to be Unicode only.
void killProcessByName(TCHAR *filename)
/* ... */
if (_tcscmp(pEntry.szExeFile, filename) == 0) /* replaced strcmp */
/* ... */
#include <windows.h> /* needed in order to use TEXT() macro */
/* ... */
TCHAR *proccc = TEXT("firefox.exe"); /* TEXT() is a <windows.h> macro */
Use TCHAR type everywhere if the functions involved are not WCHAR specific. That would allow project setting to build either ANSI/ASCII (not set) or Unicode.
Note that Process32First and Process32Next use TCHAR.
This is mostly for legacy, since Windows 2000 and later API functions use Unicode internally, converting ANSI/ASCII to Unicode as needed, while Windows NT and older API functions use ANSI/ASCII.
However, typically many or most text files (such as source code) are ANSI/ASCII and not Unicode, and it's awkward to have to support Unicode for Windows API and then ANSI/ASCII for text files in the same program, and for those projects I use ANSI/ASCII.
By using the TCHAR based generic types, I can share common code with projects that use Unicode and with projects that use ANSI/ASCII.

The error message is clear: you have an error at this precise line:
if (strcmp(pEntry.szExeFile, filename) == 0)
Because your arguments are not of char* type as expected by strcmp but WCHAR* types. You should use wcscmp instead, which is basically the same function, but working with wchar_t* type.

szExeFile in tagPROCESSENTRY32 is declared as TCHAR, which will be a 1-byte char when compiling with Character Set set to 'Not Set' or 'Multibyte'. Set Character Set in your project settings to Use Unicode Character Set to fix the problem.
Also, use wcscmp to compare WCHAR types.

Related

When to use _Notnull_ in C++?

Can someone provide insight when to use _Notnull_? I'm using Visual Studio 2019 and here is my code:
#include <windows.h>
#include <vector>
void WriteIt(_Notnull_ CONST WCHAR* sMsg, _Notnull_ CONST WCHAR* sFileName)
{
FILE* stream;
errno_t err = _wfopen_s(&stream, sFileName, L"a+");
if (err == 0)
if (stream)
{
fwprintf_s(stream, L"%s", sMsg);
fclose(stream);
}
}
int main()
{
WCHAR *sMessage = new WCHAR[16]();
WCHAR *sFile = NULL;
sFile = NULL;
WriteIt(sMessage, sFile);
}
Yet, the _Notnull_ lets the function run. I can't find any documentation on how/why to use it with examples.
Thanks #François Andrieux. Looks like it is used when doing a code analysis from within Visual Studio, where the analyzer can pinpoint if an incoming pointer could be NULL. Here is what the code analyzer says with _Notnull_ is included: Warning C6387 'sFile' could be '0': this does not adhere to the specification for the function 'WriteIt'. Very helpful!

How to share a directory using C++ so everyone can access

I'm trying to make a program so that when it run, it will create a new folder on C://. I also want to add a feature where the folder can have a shared permission to everyone. So, everyone can access and read/write
I've tried using netshareadd but I always got a compiler warning, how do I get rid of it?
This is creating new directory code :
#include <direct.h>
int main()
{
mkdir("c:/scan");
return 0;
}
This is the netshareadd code :
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <stdio.h>
#include <lm.h>
#pragma comment(lib, "Netapi32.lib")
void wmain( int argc, TCHAR *argv[ ])
{
NET_API_STATUS res;
SHARE_INFO_2 p;
DWORD parm_err = 0;
if(argc<2)
printf("Usage: NetShareAdd server\n");
else
{
//
// Fill in the SHARE_INFO_2 structure.
//
p.shi2_netname = TEXT("TESTSHARE");
p.shi2_type = STYPE_DISKTREE; // disk drive
p.shi2_remark = TEXT("TESTSHARE to test NetShareAdd");
p.shi2_permissions = 0;
p.shi2_max_uses = 4;
p.shi2_current_uses = 0;
p.shi2_path = TEXT("C:\\scan");
p.shi2_passwd = NULL; // no password
//
// Call the NetShareAdd function,
// specifying level 2.
//
res=NetShareAdd(argv[1], 2, (LPBYTE) &p, &parm_err);
//
// If the call succeeds, inform the user.
//
if(res==0)
printf("Share created.\n");
// Otherwise, print an error,
// and identify the parameter in error.
//
else
printf("Error: %u\tparmerr=%u\n", res, parm_err);
}
return;
}
22 22 D:\kerja\NETSHARE.cpp [Warning] deprecated conversion from
string constant to 'LPWSTR {aka wchar_t*}' [-Wwrite-strings]
This is the warning that I always got when compiling the netshareadd code
NetShareAdd requires a non const parameter. Some Windows APIs modify the passed buffer (or are way old) so you need a wchar_t*, not a const wchar_t* which is what a L"string" produces.
Solution, copy the const wchar_t* into a vector and pass the vector's data() member to the function (don't forget the null terminator).

Incompatible with parameter of type "LPCWSTR"

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <dos.h>
using namespace std;
class Dir
{
public:
char* cat;
Dir()
{
cout << "(C:/*)\n";
cat = new char[50];
cin >> cat;
}
void virtual ShowFiles()
{
}
};
class Inside : public Dir
{
public:
void virtual ShowFiles()
{
HANDLE hSearch;
WIN32_FIND_DATA pFileData;
hSearch = FindFirstFile(cat, &pFileData);
if (hSearch != INVALID_HANDLE_VALUE)
do
{
// if ((pFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
cout << pFileData.cFileName << "\n";
} while (FindNextFile(hSearch, &pFileData));
FindClose(hSearch);
}
};
int main()
{
Dir *obj1[2];
obj1[1] = new Inside;
obj1[1]->ShowFiles();
return 0;
}
So I have a program, I need to show with dynamic char cat all file in directory, but it is compilable in Borland C++ but in Visual Studio 15 + Resharper it doesn't work. Severity Code Description Project File Line
Error (active) argument of type "char *" is incompatible with parameter of type "LPCWSTR"
To compile your code in Visual C++ you need to use Multi-Byte char WinAPI functions instead of Wide char ones.
Set Project -> Properties -> Advanced (or. General for older versions) -> Character Set option to Use Multi-Byte Character Set
also see the screenshot
I actually found another way to resolve this error since above method did not work for me.
I casted all my constant character strings with (LPCWSTR). The solution looks like this
Earlier
MessageBox(NULL,"Dialog creation failed! Aborting..", "Error", MB_OK);
After casting to LPCWSTR
MessageBox(NULL, (LPCWSTR) "Dialog creation failed! Aborting..", (LPCWSTR) "Error", MB_OK);
So just copying the (LPCWSTR) and pasting wherever this error was generated resolved all my errors.
Another way to come by this issue, is to use the Lmacro in front of your string.
MessageBox(NULL, L"Dialog creation failed! Aborting..", L"Error", MB_OK);
See: What does the 'L' in front a string mean in C++?
or
L prefix for strings in C++
you can use wchar_t
class Dir
{
public:
wchar_t* cat;
Dir()
{
wcout << "(C:/*)\n";
cat = new wchar_t[50];
wcin >> cat;
}
void virtual ShowFiles()
{
}
};
In Visual Studio 2013 and later, the MFC libraries for multi-byle character encoding (MBCS) will be provided as an add-on to Visual Studio
It will work for any settings:
#include <tchar.h>
MessageBox(NULL, _T("Dialog creation failed! Aborting.."), _T("Error"), MB_OK);

NetUserChangePassword C++

I would like to change user password on my Windows 7 PC using C++.
But when I compile it gets error:
undefined reference to 'NetUserChangePassword'
[Error] ld returned 1 exit status.`
How can I fix it?
Here is the MSDN page with the NetUserChangePassword function:
#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, "netapi32.lib")
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <lm.h>
bool ChangeUserPassword(LPCWSTR OldPassword, LPCWSTR NewPassword)
{
NET_API_STATUS nStatus;
LPTSTR lp = new TCHAR[256];
DWORD dw = 256;
GetUserName(lp, &dw);
nStatus = NetUserChangePassword(NULL, lp, OldPassword, NewPassword);
delete[] lp;
if (nStatus == NERR_Success)
return true;
return false;
}
int main(int argc, char** argv)
{
LPCWSTR Old_P = L"C";
LPCWSTR New_P = L"D";
ChangeUserPassword(Old_P, New_P);
return 0;
}
I tried to link to the project the winapi32.dll in two ways
i tried to add using the project option
i tried to add following line
HINSTANCE hInst = LoadLibrary( L"C:\\Windows\\System32\\netapi32.dll ");
but i get always the same error
The requirements section of the MSDN topic you linked to states that you must link the Netapi32.lib library. That is the step that you have missed and explains the missing external error.
As to how to resolve the problem it is hard to say for sure. You are not using the MS compiler and so the #pragma approach won't work. Consult the docs for your compiler/linker to work out how to link this library.
It looks like you are using a GCC based compiler and so need to add -lnetapi32 to the options.

error C2664: 'MessageBoxA' : cannot convert parameter 2 from 'const wchar_t [58]' to 'LPCSTR'

guys whay i have this to error and how i can fix that?!
but before that i say i searched in the net and find a solution for my problem such as:
the properties, and navigate to Configuration Properties > General. Switch Character Set to "Use Multi-Byte Character Set".
but also i have same error?!!
The error's:
Error 7 error C2664: 'MessageBoxA' : cannot convert parameter 2 from 'const wchar_t [58]' to 'LPCSTR'
Error 8 error C2664: 'int std::basic_string<_Elem,_Traits,_Ax>::compare(const std::basic_string<_Elem,_Traits,_Ax> &) const' : cannot convert parameter 1 from 'CHAR [260]' to 'const std::basic_string<_Elem,_Traits,_Ax> &'
and my code is:
#include "StdInc.h"
#include<fstream>
#include<sstream>
#include<string>
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<Windows.h>
#include<TlHelp32.h>
using std::ifstream;
using std::string;
using std::getline;
using std::ios;
using std::cerr;
using std::cout;
using std::endl;
using std::fixed;
using std::left;
using std::right;
using std::showpoint;
using std::cin;
class check {
public :
void check_seta () {
ifstream cfgm2("finfin.cfg",ios::in);
string cfgLine;
while (getline(cfgm2,cfgLine)) {
if (string::npos != cfgLine.find("seta mamamia")){
if (cfgLine.at(19) == '0'){
MessageBox(NULL , L"lol not do that",NULL,MB_ICONERROR);
std::wstring Processname(L"mod.exe");
DWORD ProcessId = FindProcessId(Processname);
HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, TRUE ,ProcessId);
TerminateProcess(pHandle,0);
CloseHandle(pHandle);
}
break;
}
}
}
DWORD FindProcessId(const std::wstring& processName)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if ( processesSnapshot == INVALID_HANDLE_VALUE )
return 0;
Process32First(processesSnapshot, &processInfo);
if ( !processName.compare(processInfo.szExeFile) )
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while ( Process32Next(processesSnapshot, &processInfo) )
{
if ( !processName.compare(processInfo.szExeFile) )
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
};
In the project settings you did not select Unicode. So you have the narrow sharacter version of the WIN32 API. MessageBox maps to MessageBoxA, and the process info structure has LPCSTR in it. If you change the setting those become MessageBoxW and LPCWSTR, and the code will compile (or you get other errors elsewhere).
If you mean to use that the A versions, use char instead of wchar_t, string instead of wstring, "xxx" instead of L"xxxx" all around.
You're using wide string literals (L"..."), so you must actually use the Unicode character set in the Project settings you mention. This will define _UNICODE and make all Windows function-name macros expand to the wide-character variants (suffix W).
Or, preferably, if you know you want to use wide strings, just call the wide-char versions directly. That is, use MessageBoxW instead of MessageBox, etc. for other char-width-specific functions.
In your project properties in Visual Studio, go to Configuration Settings > C/C++ > Preprocessor > Preprocessor Definitions and make sure UNICODE; is defined. That fixed a similar error for me.