C4996 ошибка fopen

Many of Microsoft’s secure functions, including fopen_s(), are part of C11, so they should be portable now. You should realize that the secure functions differ in exception behaviors and sometimes in return values. Additionally you need to be aware that while these functions are standardized, it’s an optional part of the standard (Annex K) that at least glibc (default on Linux) and FreeBSD’s libc don’t implement.

However, I fought this problem for a few years. I posted a larger set of conversion macros here., For your immediate problem, put the following code in an include file, and include it in your source code:

#pragma once
#if !defined(FCN_S_MACROS_H)
   #define   FCN_S_MACROS_H

   #include <cstdio>
   #include <string> // Need this for _stricmp
   using namespace std;

   // _MSC_VER = 1400 is MSVC 2005. _MSC_VER = 1600 (MSVC 2010) was the current
   // value when I wrote (some of) these macros.

   #if (defined(_MSC_VER) && (_MSC_VER >= 1400) )

      inline extern
      FILE*   fcnSMacro_fopen_s(char *fname, char *mode)
      {  FILE *fptr;
         fopen_s(&fptr, fname, mode);
         return fptr;
      }
      #define fopen(fname, mode)            fcnSMacro_fopen_s((fname), (mode))

   #else
      #define fopen_s(fp, fmt, mode)        *(fp)=fopen( (fmt), (mode))

   #endif //_MSC_VER

#endif // FCN_S_MACROS_H

Of course this approach does not implement the expected exception behavior.

sektor2009

3 / 3 / 2

Регистрация: 15.03.2009

Сообщений: 347

1

11.05.2014, 16:57. Показов 96979. Ответов 8

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

error C4996: ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
не нравится вот эта строчка

C++
1
2
a=fopen("Pole.txt","r");
    bb=fopen("rezult.txt","w");

читал что надо писать fopen_s() Но тогда не нравится ему что в нутри скобок) не принимает char



0



232 / 232 / 69

Регистрация: 30.09.2012

Сообщений: 545

11.05.2014, 17:19

2

sektor2009, Вам же компилятор сам сказзал, что нужно сделать. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
Курсор на имя вашего проекта, жать ПКМ, выбираем свойства — Свойства конфигурации -> C/C++ -> Препроцессор и в определения препроцессора добавляем ;_CRT_SECURE_NO_WARNINGS , после чего ОК и ошибки нет.



5



3 / 3 / 2

Регистрация: 15.03.2009

Сообщений: 347

11.05.2014, 17:44

 [ТС]

3

не помогло (((
что делать??



0



7 / 4 / 14

Регистрация: 05.02.2014

Сообщений: 131

11.05.2014, 17:59

4

sektor2009,
#include <iostream>
#include <fstream>

fstream f;
f.open(filename, ios: out);

Добавлено через 1 минуту
f.close();

где filename — имя файла

лучше всего сделать
char filename[32];
cout <<«Name file n»;
cin >> filename;



0



232 / 232 / 69

Регистрация: 30.09.2012

Сообщений: 545

11.05.2014, 18:03

5

sektor2009, Move to front, алгоритм на C++, error C4996: ‘fopen’: Посмотрите, что пишет Croessmah. Когда ошибка станет варнингом( то есть предупреждением) её можно будет убрать тем, что я писал или же перед всеми инклудами вставить строчку #define _CRT_SECURE_NO_WARNINGS Это снимет предупреждения.



4



degree128

1 / 1 / 0

Регистрация: 03.09.2018

Сообщений: 71

13.10.2018, 14:58

6

Для решения проблемы нужно написать

C++
1
2
FILE *a;
 fopen_s(a,"FIlename","r");



0



AlinDen

0 / 0 / 0

Регистрация: 05.05.2019

Сообщений: 74

25.02.2021, 09:40

7

C++
1
2
3
4
5
6
7
8
9
10
char InFileName[80]; // Имя входного файла
    printf_s("Введите имя входного файла: ");
    cin >> InFileName;
    FILE *InFile;
    fopen_s(InFile, "InFileName", "r"); // Открываем файл для чтения
    if (!InFile) {
        printf_s("Ошибка при открытии файлаn");
        _getch();
        return;
    }

Ошибка (активно) E0167 аргумент типа «FILE *» несовместим с параметром типа «FILE **»



0



Volga_

Модератор

Эксперт CЭксперт С++

4659 / 2676 / 1439

Регистрация: 14.12.2018

Сообщений: 4,968

Записей в блоге: 1

25.02.2021, 09:52

8

Цитата
Сообщение от AlinDen
Посмотреть сообщение

fopen_s(InFile, «InFileName», «r»); // Открываем файл для чтения
    if (!InFile) {

Надо:

C++
1
2
3
errno_t err = fopen_s(&InFile, InFileName, "r");
    if (err)
    {



0



AlinDen

0 / 0 / 0

Регистрация: 05.05.2019

Сообщений: 74

25.02.2021, 10:22

9

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
void Menu7()
{
    FILE *InFile;
    char InFileName[80]; // Имя входного файла
    printf_s("Введите имя входного файла: ");
    cin >> InFileName;
    
    errno_t err = fopen_s(&InFile, InFileName, "r"); // Открываем файл для чтения
    if (err) {
        printf_s("Ошибка при открытии файлаn");
        _getch();
        return;
    }
 
    int i, j;
    for (i = 1; i <= N; i++) // Заполняем индексный массив
        ind[i] = i;
 
    int m[N + 1]; // Массив частот символов
    float _p[N + 1]; // Массив для хранения исходных вероятностей
 
    for (i = 1; i <= N; i++) // Обнуляем массив частот символов
        m[i] = 0;
    char _c;
    while (!feof(InFile)) {
        fscanf_s(InFile, "%c", &_c); // Читаем символ из файла
        if (_c != 10 && _c != 13)
            m[GetNo(_c)]++;
    }
    fclose(InFile);
    int s = 0; // Сумма всех частот
    for (i = 1; i <= N; i++)
        s += m[i];
    for (i = 1; i <= N; i++)
        p[i] = (float)m[i] / s;
    SortP(); // Сортируем массив вероятностей
    for (i = 1; i <= N; i++) // Сохраняем исходные вероятности
        _p[i] = p[i];
 
    for (i = 1; i <= N; i++) {
        for (j = 1; j <= N; j++)
            c[i][j] = 0;
        l[i] = 0;
    }
    Huffman(N);
 
    char OutFileName[80];  // Имя выходного файла
    printf_s("Введите имя выходного файла: ");
    cin >> OutFileName;
    FILE *OutFile;
    errno_t er = fopen_s(&OutFile, OutFileName, "w"); // Открываем файл для записи
    if (er) {
        printf_s("Ошибка при создании файлаn");
        _getch();
        return;
    }
 
    errno_t errr = fopen_s(&InFile, "InFileName", "r");
    while (errr) { // Кодируем файл
        fscanf_s(InFile, "%c", &_c); // Читаем символ из файла
        if (_c != 10 && _c != 13) {
            int no = ind[GetNo(_c)];
            for (j = 1; j <= l[no]; j++)
                fprintf(OutFile, "%d", c[no][j]);
        }
        else
            fprintf(OutFile, "%c", _c);
    }
    fclose(InFile);
    fclose(OutFile);
 
    _getch();
    return;
}

Ошибка LNK2019 ссылка на неразрешенный внешний символ WinMain в функции «int __cdecl invoke_main(void)» (?invoke_main@@YAHXZ)



0



  • Forum
  • Windows Programming
  • Fopen giving error

Fopen giving error

void In(void) //read the image
{
int i, j;
double el;
char buff[255];
stream = fopen(«test.txt», «r»); //skeltonize -> newedg.txt & normal myFile1
for (j = 0; j < ny; j++) //row
for (i = 0; i < nx; i++) //col
{
fscanf(stream, «%lf», &el);
I[i][j] = el;
}
fclose(stream);
}

This is the aspect of the code and this is the error i get:

Error C4996 ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead.

Error C4996 ‘fscanf’: This function or variable may be unsafe. Consider using fscanf_s instead.

If you are using Visual Studio you can #define _CRT_SECURE_NO_WARNINGS before your #include files.

Not recommended. It is using a bomb to swat a fly. And doesn’t fix the problems with the functions, you can still have buffer overruns.

OR

Use C11’s fopen_s() and fscanf_s() function that was created to prevent buffer overruns. As suggested in the error messages.

https://en.cppreference.com/w/c/io/fopen
https://en.cppreference.com/w/c/io/fopen

Still not working. Any other solution

Don’t use C code. Write C++ instead. Something like this should do it, assuming I is an array of some sensible type.

1
2
3
4
5
6
7
8
ifstream inputFile("test.txt");
for (j = 0; j < ny; j++) //row
{
  for (i = 0; i < nx; i++) //col
  {
    inputFile >>  I[i][j];
  }
}

Last edited on

You should check if and why fopen fails.

1
2
3
4
5
6
stream = fopen("test.txt", "r"); 
if (stream == NULL)
{
  perror(NULL); // #include <stdio.h>
  return;
}

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • I saw this example to open file:

    int main(){

    FILE * pFile; pFile = fopen("myfile.txt", "w"); if (pFile != NULL) { fputs("fopen example", pFile); fclose(pFile); } return 0;

    }

    But when I run this code was a error:

    Error
    C4996
    ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

    So I used  ‘fopen_s’ and ran this code:

    int main(){

    FILE * pFile; FILE * stream; pFile = fopen_s(&stream,"myfile.txt", "w"); if (pFile != NULL) { fputs("fopen example", pFile); fclose(pFile); }

    return 0;

    }

     But was a this error:

    Error C2440
    ‘=’: cannot convert from ‘errno_t’ to ‘FILE *’

    What I need to do for corect compile this code?

    • Edited by

      Sunday, July 17, 2016 2:14 PM

Answers

  • The fopen_s function return type is errno_t and you’re trying to assign it to a variable of type FILE *, which is what the compiler is telling you.

    Have a look at the example on the
    fopen_s function documentation page to see how to use it correctly.


    Cheers
    Eddie

    • Proposed as answer by
      RLWA32
      Sunday, July 17, 2016 4:12 PM
    • Marked as answer by
      Hart Wang
      Monday, July 25, 2016 3:06 AM

  • What I need to do for corect compile this code?

    1. Read the documentation for fopen_s.

    2. Curse (or thank Microsoft for easy and intuitive API if you like)

    3. Fix your code

    — pa

    • Proposed as answer by
      RLWA32
      Sunday, July 17, 2016 4:12 PM
    • Marked as answer by
      Hart Wang
      Monday, July 25, 2016 3:06 AM

System information (version)
  • OpenCV => 3.2.0 rc (Latest version)
  • Operating System / Platform => Windows10 64bit
  • Compiler => Visual Studio 2015 Update3
Detailed description

Source: %OPENCV_PATH%includeopencv2flannlogger.h 67
Error C4996 ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Steps to reproduce

Build below code with opencv_flann.

#include <Windows.h>
#include <opencv2/opencv.hpp>

void main(int argc, char* argv[])
{
}

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nCmd)
{
    main(0,NULL);
}
logger.h : Original code.
66: stream = fopen(name,"w");
67: if (stream == NULL) {
68:     stream = stdout;
69: }
logger.h : Fixed code.
66: #if _MSC_VER >= 1500
67:     errno_t error;
68:     error = fopen_s(&stream, name, "w");
69:     if (error != 0) {
70:         stream = stdout;
71:     }
72: #else
73:     stream = fopen(name,"w");
74:     if (stream == NULL) {
75:         stream = stdout;
76:     }
77: #endif

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • C4996 visual studio ошибка
  • C4996 c ошибка как отключить
  • C4996 c ошибка как исправить
  • C4996 c ошибка strtok

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии