You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现C++从URL读取远程TXT并转为const char*数组?

如何从远程TXT文件读取内容并生成有效的const char*数组

你的代码存在三个核心问题导致wordlist无法正常工作:

  • 字符串查找的语法错误,非法的分隔符写法导致解析失败;
  • 子字符串提取逻辑错误,无法正确获取双引号内的单词;
  • 悬空指针问题:parseAndPopulate里的words是局部vector,函数结束后销毁,c_str()返回的指针失效,导致wordlist指向无效内存。

以下是修正后的完整代码:

#include <iostream>
#include <string>
#include <vector>
#include <Windows.h>
#include <wininet.h>
#include <cstring>

#pragma comment(lib, "wininet.lib")

// 解析输入字符串并为wordlist分配内存、填充内容
void parseAndPopulate(const std::string& input, const char** wordlist, int size) {
    std::vector<std::string> words;
    size_t start = 0;
    size_t end = 0;

    // 跳过开头的双引号
    if (!input.empty() && input[start] == '"') {
        start++;
    }

    while ((end = input.find('"', start)) != std::string::npos) {
        // 提取双引号之间的单词
        words.push_back(input.substr(start, end - start));
        // 跳过当前双引号和后续的",分隔符
        start = end + 1;
        if (start + 1 < input.size() && input[start] == ',' && input[start + 1] == '"') {
            start += 2;
        } else {
            break;
        }
    }

    // 检查单词数量是否匹配
    if (words.size() != size) {
        std::cerr << "错误:文件中的单词数量与指定大小不匹配\n";
        return;
    }

    // 为每个单词分配独立内存并复制内容,避免悬空指针
    for (int i = 0; i < size; ++i) {
        wordlist[i] = new char[words[i].size() + 1];
        std::strcpy(const_cast<char*>(wordlist[i]), words[i].c_str());
    }
}

// 释放wordlist的内存,避免泄漏
void freeWordlist(const char** wordlist, int size) {
    for (int i = 0; i < size; ++i) {
        if (wordlist[i]) {
            delete[] wordlist[i];
        }
    }
}

int main() {
    const int size = 3;
    const char* wordlist[size] = {nullptr}; // 初始化指针为空

    // 注意补充http://协议前缀,WinINet需要完整URL
    const char* url = "http://10.10.10.10/file.txt";

    HINTERNET hInternet = InternetOpenA("HTTPGET", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (hInternet != NULL) {
        HINTERNET hUrlFile = InternetOpenUrlA(hInternet, url, NULL, 0, INTERNET_FLAG_RELOAD, 0);
        if (hUrlFile != NULL) {
            std::string readBuffer;
            char buffer[1024];
            DWORD bytesRead = 0;

            while (InternetReadFile(hUrlFile, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {
                readBuffer.append(buffer, bytesRead);
            }

            InternetCloseHandle(hUrlFile);

            parseAndPopulate(readBuffer, wordlist, size);

            // 输出测试
            for (int i = 0; i < size; ++i) {
                if (wordlist[i]) {
                    std::cout << wordlist[i] << std::endl;
                }
            }

            // 必须释放手动分配的内存
            freeWordlist(wordlist, size);
        } else {
            std::cerr << "错误:无法打开URL " << url << std::endl;
        }

        InternetCloseHandle(hInternet);
    } else {
        std::cerr << "错误:无法初始化WinINet" << std::endl;
    }

    return 0;
}

关键修改说明:

  1. 修复解析逻辑:正确跳过开头双引号,查找每个单词的结束双引号,再跳过分隔符",,确保准确提取每个单词。
  2. 解决悬空指针:为每个单词手动分配内存,用strcpy复制字符串内容,这样即使局部vector销毁,wordlist的指针依然指向有效内存。
  3. 添加内存释放:新增freeWordlist函数,在使用完wordlist后释放内存,避免内存泄漏。
  4. 修正URL:原URL缺少http://前缀,WinINet需要完整的协议标识才能正确建立连接。

内容的提问来源于stack exchange,提问作者Ricky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:25:56