gpt4 book ai didi

C - 将 'string' 而不是 char 分配给 open 函数使用的变量

转载 作者:行者123 更新时间:2023-11-30 18:15:24 25 4
gpt4 key购买 nike

我有一个由以下内容组成的变量输出:

//main function
char *output; //this is how output is defined

//these 3 lines are in some function call
char cmd[50] // this is how cmd is defined
cmd = "test.txt" //cmd is not initialized this way (cmd = "text.txt").
//Rather, there is some function call that passes in the
//&output and does some things, inevitably updating cmd
//by adding one character at a time. In this example it will
//go cmd = "t", cmd = "te", ... cmd = "test.txt",
//cmd = "test.txt"
*output = cmd; //then at the end of the function I try to set the contents of
//output to the cmd.

然后我尝试调用 open 方法:

int outfile;
outfile = open( *output, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP );

但这不起作用。然而这有效:

int outfile;
outfile = open( "test.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP );

当我尝试传递 *output 时,出现错误:

warning: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; remove *

但是当我尝试仅输出时,它无法正常工作。我假设输出中存储的内容只是“t”,但我需要所有这些才能使这项工作正常进行。有任何想法吗?其背景是我正在手动尝试进行重定向。

最佳答案

*输出是 - 你猜对了 - 一个字符(因为输出是“ptr to char”)cmd 是 - 你没有猜到 - 一个指向 char 的指针(因为它是一个数组)

所以你的赋值“*output = cmd”实际上不会做任何合理的事情。

尝试

strcpy(output, cmd);

或者,(更好)

strncpy(output, cmd, BUFLEN);

(确保 BUFLEN 等于输出时分配的内存,并确保输出不是局部变量)

托比亚斯

关于C - 将 'string' 而不是 char 分配给 open 函数使用的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com