我正在尝试使用getline()接收输入后从用户输入标记字符串 . 我的代码如下 . 但是,一旦我开始标记化,我就会遇到分段错误 . 我应该采用不同的方式进行令牌化,还是我在进行令牌化错误?
int main(int argc, char **argv)
{
int bytes_read = 1;
int nbytes = 10;
char *command, *flag, *pathname, *linkname;
struct stat st = {0};
char *cmd = NULL;
char *token; //Pointer
int counter = 1; //Counter variable
FILE *fp;
char mode2[] = "0750"; //To set the permission of a file/path
long j;
char mode[] = "0640"; //To set the permission of a file/path
long i;
cmd = (char *) malloc(nbytes+1);
bytes_read = getline(&cmd, &nbytes, stdin);
if(bytes_read == -1) {
puts("Error with command input.\n");
exit(EXIT_FAILURE);
}
//User input is tokenized to determine the proper commands are entered and executed
token = strtok(cmd, " "); //Input is tokenized by white spaces.
if(token == NULL)
{
printf("Error with command input.\n");
exit(EXIT_FAILURE);
}
token = strtok(cmd, " ");
if(token != NULL)
strcpy(flag, token);
token = strtok(cmd, " ");
if(token != NULL)
strcpy(pathname, token);
token = strtok(cmd, " ");
if(token != NULL)
strcpy(linkname, token);