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

VS与Code::Blocks编译运行正常,Dev-C++及Online GDB编译报错‘fopen_s未在此作用域中声明’的问题

Fixing the 'fopen_s was not declared in this scope' Error in Dev-C++/Online GDB

Hey there, let's break down why your code works smoothly in Visual Studio but hits a snag in Dev-C++ or Online GDB, plus how to fix it right up.

The Root Cause

fopen_s is a Microsoft-specific security function tied to their C Runtime Library (CRT) extensions. It's not part of official C or C++ standards, so compilers built on GCC (like those used in Dev-C++ and Online GDB) don't recognize it by default. Visual Studio uses MSVC, which supports these Microsoft extensions out of the box—hence why it works there.

Solutions to Fix the Error

Option 1: Swap fopen_s for Standard fopen

The quickest fix is to switch to the cross-compiler standard fopen function. Just remember to add a check to make sure the file opened successfully (a good practice no matter what):

// Replace this line:
// fopen_s(&f, "myfile2.txt", "rb");

// With this:
FILE* f = fopen("myfile2.txt", "rb");
if (f == NULL) {
    cerr << "Failed to open file!" << endl;
    return 1; // Handle the error however makes sense for your program
}

Since your code already uses C++ features like std::ifstream and std::ofstream, why not replace the C-style file operations entirely with C++ streams? This makes your code more consistent and avoids platform-specific functions. Here's how to rewrite that section:

if (c == 101) {
    std::ifstream file("myfile2.txt", std::ios::binary | std::ios::ate);
    if (!file.is_open()) {
        cerr << "Unable to open file" << endl;
        return 1;
    }

    std::streampos fsize = file.tellg();
    file.seekg(0, std::ios::beg);

    std::vector<char> file_content(fsize + 1);
    file.read(file_content.data(), fsize);
    file_content[fsize] = '\0';
    file.close();

    // Rest of your logic here (use file_content.data() as your char array)
}

Bonus: Fix a Critical Logic Bug in Your Code

I spotted a bug that will mess up your results no matter which compiler you use:

int len = sizeof(string) / sizeof(*string);

Since string is a char* pointer, sizeof(string) returns the size of the pointer (4 or 8 bytes, depending on your system), not the length of the file content. Use the fsize variable you already calculated instead:

int len = fsize;

Extra Tip: The getMedian Function

While not related to the compilation error, your getMedian function currently returns arr[5] directly. For a 9-element array, the median should be the 5th element (index 4) of the sorted array, not the unsorted index 5. You might want to add sorting logic there if you're aiming for a correct median calculation.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:57:42