1

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?

3
  • 1
    Please paste your code here. Don't make us visit an external site to see your code. Commented Mar 3, 2012 at 4:22
  • I know, firefox has been acting weird for me, trying to figure out why. Commented Mar 3, 2012 at 4:24
  • Report errors on cerr; that's what it is designed for. And, in theory, it would be a good idea to use FILE *Data = OpenFile("data.txt"); and to close the file before exiting. In practice, in this context, it does not matter much, but in many contexts, not freeing allocated resources is a bad idea, and RAII (Resource Acquisition Is Initialization) suggests the initialize on definition notation. Commented Mar 3, 2012 at 4:32

1 Answer 1

12

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.