将字符串文字传递给函数“char *”并获取编译器警告

时间:2012-03-03 04:21:24

标签: c++

只是一个语法问题,这是我的代码片段。 (抱歉,浏览器不允许我正确粘贴到堆栈溢出中。)

#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;
}

编译时,我收到以下警告:

$ 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]
$

我哪里错了?

1 个答案:

答案 0 :(得分:11)

C ++中的字符串文字类型为“ n const char的数组”(其中 n 是字符串中的字符数,包括终止NUL )。以这种方式声明你的功能:

FILE *OpenFile(const char *Filename)