检查文件是否存在的Visual c++ DLL

Visual C++ DLL that checks if file exists

本文关键字:Visual c++ DLL 存在 文件 是否 检查      更新时间:2023-10-16

我制作了这个dll文件,试图检查文件是否存在。但是,即使我手动创建文件,我的dll仍然找不到它。

我的dll检索正在运行的程序的进程id,并查找以pid命名的文件。

谁能告诉我我错过了什么?

代码:

#include <Windows.h>
#include <winbase.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int clientpid = GetCurrentProcessId();
ifstream clientfile;
string clientpids, clientfilepath;
VOID LoadDLL() {
    AllocConsole();
    freopen("CONOUT$", "w", stdout);
    std::cout << "Debug Start" << std::endl;
    std::ostringstream ostr;
    ostr << clientpid;
    clientpids = ostr.str();
    ostr.str("");
    TCHAR tempcvar[MAX_PATH];
    GetSystemDirectory(tempcvar, MAX_PATH);
    ostr << tempcvar << "\" << clientpids << ".nfo" << std::endl;
    clientfilepath = ostr.str();
    //clientfile.c_str()
    ostr.str("");
    std::cout << "Start search for: " << clientfilepath << std::endl;
    FOREVER {
        clientfile.open(clientfilepath,ios::in);
        if(clientfile.good()) {
            std::cout << "Exists!" << std::endl;
        }
        Sleep(10);
    };
}

假设您正在使用UNICODE

我认为问题出在下面一行:
ostr << tempcvar << "\" << clientpids << ".nfo" << std::endl;
tempcvar是一个字符,也许你正在使用unicode,所以这意味着tempcvar是一个宽字符。

您在ostr中插入tempcvar的结果不是您所期望的(您也将多字节与widechar混合)。解决这个问题的方法是将tempcvar转换成多字节字符串(const char*char*…)

根据您的代码查看这个示例(查看char到多字节char之间的转换)

VOID LoadDLL() {
AllocConsole();
freopen("CONOUT$", "w", stdout);
std::cout << "Debug Start" << std::endl;
std::ostringstream ostr;
ostr << clientpid;
clientpids = ostr.str();
ostr.str("");
TCHAR tempcvar[MAX_PATH];
GetSystemDirectory(tempcvar, MAX_PATH);
// Convertion between tchar in unicode (wide char) and multibyte
wchar_t * tempcvar_widechar = (wchar_t*)tempcvar;
char* to_convert;
int bytes_to_store = WideCharToMultiByte(CP_ACP,
    0,
    tempcvar_widechar,
    -1,NULL,0,NULL,NULL);
to_convert = new char[bytes_to_store];
WideCharToMultiByte(CP_ACP,
    0,
    tempcvar_widechar,
    -1,to_convert,bytes_to_store,NULL,NULL);
// Using char* to_convert that is the tempcvar converted to multibyte
ostr << to_convert << "\" << clientpids << ".nfo" << std::endl;
clientfilepath = ostr.str();
//clientfile.c_str()
ostr.str("");
std::cout << "Start search for: " << clientfilepath << std::endl;
FOREVER {
    clientfile.open(clientfilepath,ios::in);
    if(clientfile.good()) {
        std::cout << "Exists!" << std::endl;
    }
    Sleep(10);
};
}

如果这个例子对你不起作用,你可以搜索更多关于宽字符串到多字节字符串转换的信息。
检查你是否在使用Unicode,如果是,也许这是你的问题。

如果您不使用unicode,则代码中的问题可能是打开文件。

希望能有所帮助!