I write code as direction on MSDN, but it doesn't work. It can't load an image and save an image as bmp.
#include "stdafx.h"
#include "atlimage.h"
#include "cstdio"
#include "fstream"
int _tmain(int argc, _TCHAR* argv[])
{
CImage m_image1;
CImage m_image2;
char *srcFile = "C:\\Users\\TYZRPVX\\Desktop\\test.jpg";
const char *tarFile = "C:\\Users\\TYZRPVX\\Desktop\\testBmp.bmp";
FILE *tar;
fopen_s(&tar, tarFile, "w");
m_image1.Load((LPCTSTR)(srcFile));
//m_image1.Save(_T("C:\\Users\\TYZRPVX\\Desktop\\testBmp.bmp"));
m_image1.Save(_T("C:\\Users\\TYZRPVX\\Desktop"),Gdiplus::ImageFormatBMP);
return 0;
}
You're probably compiling with Unicode enabled which the default when creating a new project in Visual Studio. This makes your cast to LPCTSTR incorrect. Use wide character strings for your filenames and drop the cast.
const wchar_t *srcFile = L"C:\\Users\\TYZRPVX\\Desktop\\test.jpg";
const wchar_t *bmpFile = L"C:\\Users\\TYZRPVX\\Desktop\\testBmp.bmp";
m_image1.Load(srcFile);
m_image1.Save(bmpFile, Gdiplus::ImageFormatBMP);
Related
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.
I am trying to get the file size of a system application on windows. To test this i have created a test application that tries to get the file size of smss.exe in C:\Windows\System32\smss.exe but it fails with error: ERROR_FILE_NOT_FOUND. The file does actually exist (i have checked). I've also tried different methods for getting the file size, with: FindFirstFile, CreateFile and GetFileSizeEx. But all return the same error. I would also like to read the file contents.
What am i doing wrong?
The code:
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
__int64 getFileSize(LPWSTR filePath)
{
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesEx(filePath, GetFileExInfoStandard, &fad))
{
_tprintf(TEXT("\n CAnt get file size for file %s error %d"), filePath, GetLastError());
return 0;
}
LARGE_INTEGER size;
size.HighPart = fad.nFileSizeHigh;
size.LowPart = fad.nFileSizeLow;
return size.QuadPart;
}
int _tmain(int argc, _TCHAR* argv[])
{
_tprintf(TEXT("File size %d "), getFileSize(L"C:\\Windows\\System32\\smss.exe"));
}
As your application is 32-bit, the system redirects your path to go to SysWOW64 instead, where there is no smss.exe. While you have discovered that Wow64DisableWow64FsRedirection disables this redirection, also consider that having a 64-bit program would also do the trick.
Getting the size of a file is already answered here (can't yet add a comment to your question, so I need to write it as an answer):
How can I get a file's size in C++?
std::ifstream::pos_type filesize(const char* filename)
{
std::ifstream in(filename, std::ifstream::in | std::ifstream::binary);
in.seekg(0, std::ifstream::end);
return in.tellg();
}
I am getting the the following error "cannot convert cv::Mat to constCvArr".Here's the code.
Could anyone help in this case
What is the reason for the error? how could I correct it.
#include "stdafx.h"
#include "opencv2\calib3d\calib3d.hpp"
#include <opencv2\core\core.hpp>
#include "opencv2\imgproc\imgproc.hpp"
#include "opencv2\highgui\highgui.hpp"
#include <stdio.h>
using namespace cv;
Mat src_gray;
int _tmain(int argc, _TCHAR* argv[])
{
char *str1=(char *)malloc(500);
int nums=20;
for(int iter=0;iter<nums;iter++)
{
sprintf(str1,"training1//image%d.png",iter);
Mat img=imread(str1);
cvtColor(img,src_gray,CV_BGR2GRAY);
cv::Mat output = cv::Mat::zeros(img.rows,img.cols,img.type());
threshold(src_gray,output,128,255,THRESH_OTSU | THRESH_BINARY_INV);
char *out=(char *)malloc(500);
sprintf(out,"out%d.png",iter);
cvSaveImage(output,out);
namedWindow("threshold",1);
imshow("threshold",output);
waitKey(0);
return 0;
}
}
you're mixing old , deprecated c-api calls(bad) with the newer c++ api(good).
instead of:
cvSaveImage(output,out);
use:
imwrite(output,out);
also, whatever you malloc(), you'll have to free ;) (you got 2 memleaks there), again, avoid the whole issue:
Mat img=imread( cv::format("training1/image%d.png",iter) ); // note: *single* slash in path, or *double backslash
// ...
imwrite( cv::format("out%d.png",iter) );
I am trying to create simple c++ win32 console app(in vs2010) that calls windows installer automation api. But I am failing so far. This approach causes the "Microsoft C++ exception: _com_error at memory location" error.
How to correctly use this api? How to make it work correctly on 32 and 64 bit system with only one .exe file?
Many thanks,
Marek
#include "stdafx.h"
#include <windows.h>
#include <atlstr.h>
#import "msi.dll"
using namespace WindowsInstaller;
_bstr_t GetInstalledProduct(InstallerPtr pInstaller,_bstr_t upgradeCode){
StringListPtr installedProducts = pInstaller->GetRelatedProducts(upgradeCode);
return installedProducts->Count > 0 ? installedProducts->GetItem(0) : "";
}
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
InstallerPtr pInstaller("WindowsInstaller.Installer");
_bstr_t upgradeCode("4C34BD16-CAD4-4059-B074-777793406C5F");
_bstr_t installedProduct = GetInstalledProduct(pInstaller, upgradeCode);
StringListPtr features = pInstaller->GetFeatures(installedProduct);
::CoUninitialize();
return 0;
}
I finally found the solution. The correct way is include msi.lib in linker includes and use Msi.h from windows sdk.
#include "stdafx.h"
#include <windows.h>
#include <Msi.h>
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t productCode[255];
int result = MsiEnumRelatedProducts(L"{4C34BD16-CAD4-4059-A074-777493406C5F}", 0, 0, productCode);
wchar_t featureName[255];
wchar_t featureParent[255];
MsiEnumFeatures(productCode, 0, featureName, featureParent);
INSTALLSTATE featureState = MsiQueryFeatureState(productCode, L"FeatureName");
return 0;
}
I have a file and I want to get the size of the file. I can use only _wfopen or _wfopen_s for opening the file because my file path type is std::wstring.
FILE* p_file = NULL;
p_file=_wfopen(tempFileName.c_str(),L"r");
fseek(p_file,0,SEEK_END);
but I am getting an error
error C2220: warning treated as error - no 'object' file generated
To get rid of your error message, you need to fix the issue that is generating warning.
If you compile this code:
#include "stdafx.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
FILE* p_file = NULL;
std::wstring tempFileName = L"c:\\test.txt";
p_file=_wfopen(tempFileName.c_str(),L"r");
if(!p_file)
{
perror("Open failed.");
return 0;
}
fseek(p_file,0,SEEK_END);
fclose(p_file);
return 0;
}
You will get this warning:
warning C4996: '_wfopen': This function or variable may be unsafe. Consider using _wfopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
So, listen what it says, and do the following:
#include "stdafx.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
FILE* p_file = NULL;
std::wstring tempFileName = L"c:\\test.txt";
_wfopen_s(&p_file, tempFileName.c_str(),L"r");
if(!p_file)
{
perror("Open failed.");
return 0;
}
fseek(p_file,0,SEEK_END);
fclose(p_file);
return 0;
}
There is a way to turn off this warning by putting _CRT_SECURE_NO_WARNINGS in Project Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions, but you should always prefer safe alternatives to these functions.
Also, before fseek you should check if your p_file pointer is NULL.