#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <commdlg.h>
using namespace std;
int main() {
// 打开文件选择对话框
OPENFILENAMEA ofn;
char szFile[260] = { 0 };
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
ofn.nFilterIndex = 1;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
if (GetOpenFileNameA(&ofn) == TRUE) {
// 将 char 类型字符串转换为 wchar_t 类型字符串
int len = MultiByteToWideChar(CP_UTF8, 0, szFile, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
MultiByteToWideChar(CP_UTF8, 0, szFile, -1, wstr, len);
wstring filename(wstr);
delete[] wstr;
ifstream infile(filename);
if (!infile.is_open()) {
cout << "Failed to open file." << endl;
return 1;
}
string line;
string text;
while (getline(infile, line)) {
text += line + "\n";
}
cout << "The content of the file is:\n" << text;
infile.close();
return 0;
}
else {
cout << "User canceled the file selection dialog." << endl;
return 1;
}
}