1

我有一个 C++ 程序:

#include <iostream>
using namespace std;
int main (){
    char x [10] = "abc";
    system (sprintf ("mkdir ", "%s", x));    //error happens here, can't 
                                             //convert int to const char*
    return 0;
}

结果是:

sys.c:8:37: error: invalid conversion from ‘int’ to ‘const char*’

我在哪里将 int 转换为 char?

4

3 回答 3

3

system 需要一个 const char * 作为输入,而 sprintf 返回一个 int。这是导致您错误的问题。此外, sprintf 的第一个参数必须是一个足够大的可写缓冲区。

于 2013-01-10T09:12:53.383 回答
3

I know that the question has been answered already, but I wanted to share another approach to this, and it's too verbose for a comment :)

short example:

#include <cstdio>
#include <cstdlib>

int main()
{
    char x[] = "yourdirectory";
    /* len will contain the length of the string that would have been printed by snprintf */
    int len = snprintf(0, 0, "mkdir %s", x);

    /* casting the result of calloc to (char*) because we are in C++ */
    char *buf = (char*)calloc(len + 1, sizeof(char)); 
    /* fail if the allocation failed */
    if(!buf)
        return -1;

    /* copy to buffer */
    snprintf(buf, len + 1, "mkdir %s", x);

    /* system is evil :( */
    system(buf);

    return 0;
}

since snprintf returns the number of characters that would have been printed, giving it a length of 0 will tell you how large a buffer you have to allocate for the command.

this code will also work with arbitrary directories given by a user and will not suffer from input truncation of buffer overruns.

Take care :)

EDIT: of course, system is still evil and should never be used in "real" code ;)

于 2013-01-10T09:46:37.587 回答
1

来自sprintf文档

冲刺

int sprintf ( char * str, const char * format, ... );

sprintf() 将格式化数据写入字符串。

如果在 printf 上使用 format ,则使用相同的文本组成一个字符串,但不是打印,而是将内容作为 C 字符串存储在 str 指向的缓冲区中

str - 指向存储结果 C 字符串的缓冲区的指针。缓冲区应该足够大以包含结果字符串。

sprintf writes to the first argument, and in your case the first argument is a string literal .

Also as other answer points out, sprintf returns int and system() expects const char*

于 2013-01-10T09:17:03.347 回答