Irresponsible Newb
Irresponsible Newb

Reputation: 613

Passing string literal to function taking 'char *' and getting a compiler warning

Just a syntax question, here is my code snippet. (Sorry, browser isn't letting me paste properly into stack overflow.)

#include <iostream>     /* 'iostream.h' is deprecated. */
#include <cstring>
#include <cstdlib>
#include <cstdio>

using namespace std;    /* Required. */

FILE *OpenFile(char *Filename)
{
        FILE *FP;

        if((FP = fopen(Filename, "r")) == NULL)
        {       /* Error opening file. */
                std::cout << "[!!] Unable to open database!"
                          << " Are you sure it exists?\n"
                          << "[<<] Database Unchanged.\n";
                exit(EXIT_FAILURE);     /* End program. */
        }

        else    /* Properly opened the file. */
                return FP;
}

int main(void)
{
        FILE *Data;     /* Our database file pointer. */
        Data = OpenFile("Data.txt");
        printf("Success!\n");
        return 0;
}

When I compile, I get the following warning:

$ g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:27:28: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
$

Where am I going wrong?

Upvotes: 1

Views: 3994

Answers (1)

rob mayoff
rob mayoff

Reputation: 385590

String literals in C++ are of type “array of n const char” (where n is the number of characters in the string, including the terminating NUL). Declare your function this way:

FILE *OpenFile(const char *Filename)

Upvotes: 12

Related Questions