Code:
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
int main()
{
HWND handle = FindWindow(0 ,TEXT("window name"));
if(handle == 0)
{
MessageBox(0,TEXT("Failed to find window"),TEXT("Return"),MB_OK);
}
else
{
DWORD ID;
GetWindowThreadProcessId(handle,&ID);
HANDLE hProcess = OpenProcess(PROCESS_VM_WRITE|PROCESS_VM_OPERATION , FALSE, ID);
hProcess = OpenProcess(PROCESS_VM_READ , FALSE, ID);
if(!hProcess)
{
Beep(1000,1000);
}else {
int buffer;
if (ReadProcessMemory(hProcess,(void *)0x00963FC4,&buffer,4,NULL))
{
printf(buffer);
}
else {
MessageBox(0,TEXT("Could not Read"),TEXT("Return"),MB_OK);
}
}CloseHandle(hProcess);
}
}
I tried to make this program that reads memory address,
but I got this error:
IntelliSense: argument of type "int" is incompatible with parameter of type "const char *
I tried printf(buffer);
I tried to make string and also doesn't work.
string test;
First, try using the correct printf() call with format string:
printf("%d", buffer);
C is a statically typed language and you cannot do python-like stuff with printf() to output anything you want. The printf() function always prints only the first "const char *" argument allowing to substitute some values in this string according to the rules.
Second, I see the TEXT() macros in your code, so you might be using the Unicode strings in your project setup. If so (you should get link errors 2019/2005 in VC++), you have to use the wprintf() function:
wprintf(L"%d", buffer);
To print the std::string object you must also convert it to the "const char*". This is done by the string::c_str() call:
std::string MyString("Test");
printf("Your string is = %s", MyString.c_str());
Related
I have one problem with CString and STL's set.
It looks a bit strange to use CString and STL together, but I tried to be curious.
My code is below:
#include "stdafx.h"
#include <iostream>
#include <set>
#include <atlstr.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t line[1024] = {0};
FILE * pFile = _wfopen(L"F:\\test.txt", L"rt");
set<CString> cstr_set;
while (fgetws(line, 1024, pFile))
{
CString cstr;
swscanf(line, L"%s\n", cstr);
cstr_set.insert(cstr);
}
fclose(pFile);
cout << "count" << cstr_set.size();
return 0;
}
The contents of the test.txt is:
13245
123
2344
45
After the loop ends, cstr_set contains only one value.
It works as if cstr is static or const variable.
What is the problem?
A CString is a Microsoft implementation wrapping a character array into a C++ object to allow simpler processing.
But, swscanf is a good old C function that knows nothing about what a CString is: it just expects its arguments to be large enough to accept the decoded values. It should never be directly passed a CString.
The correct way would be:
...
#include <cstring>
...
while (fgetws(line, 1024, pFile))
{
line[wcscspn(line, L"\n")] = 0; // remove an optional end of line
CString cstr(line);
cstr_set.insert(cstr);
}
...
I'm using this GetWindowsDirectoryA Windows API function to get the location for Windows folder.
#include <iostream>
#include <string>
#include <vector>
#ifdef __WIN32
#include <fcntl.h>
#include <io.h>
#include <Windows.h>
#include <sysinfoapi.h>
#endif
std::string GetOSFolder() {
std::vector<char> buffer(MAX_PATH + 1);
GetWindowsDirectoryA(buffer.data(), MAX_PATH);
std::string windowsRoot{ buffer.data(), buffer.size() };
return windowsRoot + "/SomeFolder";
}
int main() {
std::cout << GetOSFolder() << "\n";
}
I want to concrete a folder name with the returned Windows folder string result.
windowsRoot + "/SomeFolder"
Above attempt results the following string,
C:\Windows
/SomeFolder
This seems happening because the buffer size is set to MAX_PATH which is larger than the actual string.
Is there a way to construct the string from buffer with actual string size?
You could initialize the string with the path, you wouldn't even need to know the size (which is returned by GetWindowsDirectoryA as stated in the comment section), but it's advisable to use it given that it does optimize std::string initialization.
Example:
std::string GetOSFolder() {
char buffer[MAX_PATH + 1];
const auto size = GetWindowsDirectoryA(buffer, MAX_PATH);
if (size) {
return std::string(buffer, size).append("/SomeFolder");
}
return ""; // or however you want to handle the error
}
int main() {
std::cout << GetOSFolder() << "\n";
}
Or you could avoid the second variable for buffer but you then have to resize the original buffer:
std::string GetOSFolder() {
std::string buffer(MAX_PATH + 1, 0);
auto result = GetWindowsDirectoryA(buffer.data(), MAX_PATH); // or &buffer[0] prior to C++17
if (result) {
buffer.resize(result);
return buffer.append("/SomeFolder");
}
return buffer; // will be an empty string if API call fails
}
Now, if you want to avoid resize you could still use some trickery:
std::string GetOSFolder() {
const auto size = GetWindowsDirectoryA(nullptr , 0);
if (size) {
std::string buffer(size, 0);
const auto result = GetWindowsDirectoryA(buffer.data(), MAX_PATH); // or &buffer[0] prior to C++17
if (result) {
return buffer.append("\\OtherPath");
}
}
return "";
}
Here you call GetWindowsDirectoryA twice, the first one to know the size you need for your buffer, the second to actually retrieve the path.
Note that in this last option, the first call will return the length of the string with the null terminator whereas the second call will only return the length of the string without including the null byte as is typical in WIN32 API for this type of call, it's a well-known pattern.
I'm trying to check if directory exist. I want to make it more reliable and I'm trying to use stat with predefined variable which check user name, but all the time I'm getting an error.
Here's userdir string output : /home/root/test
string userdir="/home/"+user+"/test";
struct stat st ;
if(stat(userdir, &st) == 0)
printf( "test directory exist\n" );
else
printf("test directory don't exist\n");
stat() takes a const char *, not an std::string:
if (stat(userdir.c_str(), &st) == 0)
// ^^^^^^^
If string is std::string then you need to call stat(userdir.c_str(), &st) - stat takes a C style string, not a C++ one.
Minimal example:
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
const std::string dir="/tmp";
struct stat st;
return stat(dir, &st); // Error
return stat(dir.c_str(), &st); // Correct
}
compiler : http://sourceforge.net/projects/mingwbuilds/files/
#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;
const wchar_t* readConsole(int chars_to_read) {
wchar_t* wcharFromConsole = new wchar_t[chars_to_read+1];
COORD pos = {0,0};
DWORD dwChars;
if (!ReadConsoleOutputCharacterW(
GetStdHandle(STD_OUTPUT_HANDLE),
wcharFromConsole, // Buffer where store symbols
chars_to_read, // number of chars to read
pos, // Read from row=8, column=6
&dwChars // How many symbols stored
))
{
printf("ReadConsoleOutputCharacterW failed %d\n", GetLastError());
abort();
}
wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used
wstring ws = wcharFromConsole;
return ws.c_str();
}
int main() {
for (int i = 1; i<=0x3000; i++) {
printf("wcslen: %X \n",wcslen(readConsole(i)));
}
system("pause");
}
This loop ends at 0x1FF1 and pause is not called. Removing wstring seems to do away with this problem. But I need it here for functions like trimming white-space etc.. it is not much relevant here, but why invoking wstring causes that issue anyway ? There is no error message the program simply quits.
Updated code, now loop quits at 0x2BBF
#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;
const wchar_t* readConsole(int chars_to_read) {
wchar_t* wcharFromConsole = new wchar_t[chars_to_read+1];
COORD pos = {0,0};
DWORD dwChars;
if (!ReadConsoleOutputCharacterW(
GetStdHandle(STD_OUTPUT_HANDLE),
wcharFromConsole, // Buffer where store symbols
chars_to_read, // number of chars to read
pos, // Read from row=8, column=6
&dwChars // How many symbols stored
))
{
printf("ReadConsoleOutputCharacterW failed %d\n", GetLastError());
abort();
}
wcharFromConsole [dwChars] = L'\0'; // Terminate, so string functions can be used
wstring ws = wcharFromConsole;
delete [] wcharFromConsole;
const wchar_t* wc = ws.c_str();
return wc;
}
int main() {
for (int i = 1; i<=0x3000; i++) {
printf("wcslen: %X \n",wcslen(readConsole(i)));
}
system("pause");
}
Ouch.
wstring ws = wcharFromConsole;
return ws.c_str();
Basically, you are returning a dead pointer here. The string will be destroyed on the return, so the pointer arriving at the caller will be invalid.
EDIT: you're also leaking memory, since the "new" is never deleted. But that doesn't generally cause visible problems, just increasing memory use of the program.
I'm porting a small C++ console application from windows to linux, GCC 4.3.2. When compiling I get strange error that I'm unable to solve.
Labels.cpp: In function ‘void DumpSymbols()’:
Labels.cpp:68: error: invalid conversion from ‘int’ to ‘std::_Ios_Openmode’
Labels.cpp:68: error: initializing argument 2 of ‘std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]’
Labels.cpp:
#include <string>
#include <fstream>
#include <iostream>
#include "stdafx.h"
using namespace std;
#include "Opcodes.h"
#include "Labels.h"
Label LABELS[1024];
int labelcounter = 0;
int OffsetCounter = 0;
void AddLabel(string name, int line)
{
LABELS[labelcounter].name = name;
LABELS[labelcounter].line = line;
LABELS[labelcounter].offset = OffsetCounter;
printf("Adding label: %s[0x%X]\n", name.c_str(), OffsetCounter);
labelcounter++;
}
bool IsLabel(string name)
{
for(int i=0;i<labelcounter;i++)
{
if (LABELS[i].name.compare(name) == 0)
{
return true;
}
}
return false;
}
int GetOffset(string lbl)
{
for(int i=0;i<labelcounter;i++)
{
if (LABELS[i].name.compare(lbl) == 0)
{
printf("Refers to label '%s':0x%X\n", lbl.c_str(), LABELS[i].offset);
return LABELS[i].offset;
}
}
return -1;
}
void DumpSymbols()
{
ofstream mapfile("symbols.map", ios::out|ios::beg); //this line causes error
//mapfile.write(
char numbuf1[32];
itoa(labelcounter, numbuf1, 10);
mapfile.write((string(numbuf1) + "\n").c_str(), strlen(numbuf1)+1);
for(int i=0;i<labelcounter;i++)
{
string dump;
char numbuf[32];
itoa(LABELS[i].offset, numbuf, 10);
dump = string(LABELS[i].name) + "\t" + string(numbuf) + "\n";
mapfile.write(dump.c_str(), strlen(dump.c_str()));
}
}
stdafx.h:
#pragma once
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cstdlib>
Thanks.
Just remove "|ios::beg":
ofstream mapfile("symbols.map", ios::out);
It's type is ios_base::seekdir, which is not an opening mode; it's for seeking to a position. You'll automatically be at the beginning anyway.
Is ios::beg really a valid value for the mode parameter of the ofstream constructor?
According to http://www.cplusplus.com/reference/iostream/ofstream/ofstream.html it's not.
I guess what happened is that you accidentally borrowed it from a call to ofstream::seekg (where it is a valid parameter) to enforce that the writing will start from the beginning of the file rather than the end of it.
If you are trying to force the file to be completely replaced if it already existed, try using ios::trunc instead of ios::beg.