struct args
{
char command[64];
char args[2][64];
};
int argscount = 0;
struct args* arguments;
int buffersize = 64;
char *ptoken = NULL;
char input[buffersize];
char *pstr = NULL;
int a = read(0,input,buffersize);
pstr = input;
arguments = malloc(sizeof(struct args));
if(a>0){
ptoken = strtok(&pstr," ");
strcpy(arguments->command,ptoken);
printf("TOKEN:%s\n", ptoken);
while( ptoken != NULL ) {
if(argscount > 1){break;}
ptoken = strtok(NULL, ' ');
strcpy(arguments->args[argscount],ptoken);
argscount++;
}
}
问问题
1611 次
4 回答
3
问题最有可能出现在
ptoken = strtok(&pstr," ");
strtok 的第一个参数应该是
char *
你有它作为
char **
于 2013-10-26T00:45:00.723 回答
2
read
不返回strtok
预期的空终止字符串。您将需要在输入中分配一个额外的字节来添加'\0'
. 您可以查看 的返回值read
以查看读取了多少字节,然后将 at 放置'\0'
在input[a]
.
int a = read(0,input,buffersize-1);
input[a] = '\0';
于 2013-10-26T00:37:50.887 回答
0
您的代码中有几个修复(和其他)。评论描述了我所做的更改:(如果read()
定义了函数,它可能已经构建)还添加了 main,只是为了通过错误进行编译。
#include <ansi_c.h>
struct args
{
char command[64];
char args[2][64];
};
int argscount = 0;
struct args* arguments;
size_t buffersize = 64; //changed to size_t
char *ptoken = NULL;
char input[64]; //variable initializer not allowed, changed
char *pstr = NULL;
int read(int a, char *s, size_t size);
main(void)
{
int a = read(0,input,buffersize);
pstr = input;
arguments = malloc(sizeof(struct args));
if(a>0)
{
ptoken = strtok(pstr," "); //changed &pstr to pstr
strcpy(arguments->command,ptoken);
printf("TOKEN:%s\n", ptoken);
while( ptoken != NULL ) {
if(argscount > 1){break;}
ptoken = strtok(NULL, " "); //changed ' ' to " "
strcpy(arguments->args[argscount],ptoken);
argscount++;
}
}
}
于 2013-10-26T00:59:18.533 回答
0
这是一种正常,明智的做法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct args {
char command[64];
char args[2][64];
};
int main(void) {
char input[64] = {0};
if ( read(0, input, sizeof(input) - 1) == -1 ) {
perror("unsuccessful read() operation");
return EXIT_FAILURE;
}
char * ptoken = strtok(input, " ");
if ( ptoken == NULL ) {
fprintf(stderr, "No valid input\n");
return EXIT_FAILURE;
}
struct args arguments;
strcpy(arguments.command, ptoken);
printf("COMMAND: %s\n", arguments.command);
int argscount = 0;
while ( ptoken && argscount < 2 ) {
ptoken = strtok(NULL, " ");
if ( ptoken ) {
strcpy(arguments.args[argscount], ptoken);
printf("TOKEN: %s\n", arguments.args[argscount++]);
}
}
return 0;
}
输出:
paul@local:~/src/c/scratch$ ./args
test
COMMAND: test
paul@local:~/src/c/scratch$ ./args
test this
COMMAND: test
TOKEN: this
paul@local:~/src/c/scratch$ ./args
test this one
COMMAND: test
TOKEN: this
TOKEN: one
paul@local:~/src/c/scratch$ ./args
test this one two
COMMAND: test
TOKEN: this
TOKEN: one
paul@local:~/src/c/scratch$
我将把剥离换行符作为练习留给你。
于 2013-10-26T01:49:18.147 回答