首页 > 解决方案 > 解析命令并将文件路径传递给 fopen

问题描述

问题出在我猜的指针中。请建议任何方法来接收诸如“cat serverpath or filepath”之类的命令并解析命令并将路径传递到fopen(filepath, "r").

这是服务器的代码:

time_t  start;
char    buf[BUFSIZ], *command, content;
int n,i;
FILE *fptr;

start = time(0);
(void) pthread_mutex_lock(&stats.st_mutex);
stats.st_concount++;
(void) pthread_mutex_unlock(&stats.st_mutex);
while (1) {
    bzero(buf, BUFSIZ);
    n = recv(fd, buf, BUFSIZ, 0);
    if (n < 0){
        errexit("echo read: %s\n", strerror(errno));
    }
    else{
        printf("The client message: %s\n",buf);
    }

    strtok_r (buf, " ", &command);
    printf("%s\n", buf);
    printf("%s\n",command);

    //char filename[100], c; 

    // printf("Enter the filename to open \n"); 
    // scanf("%s", command); 

    // Open file 
    fptr = fopen(command, "r"); 
    if (fptr == NULL) 
    { 
        printf("Cannot open file \n"); 
        exit(0); 
    } 

    // Read contents from file 
    content = fgetc(fptr); 
    while (content != EOF) 
    { 
        printf ("%c", content); 
        content = fgetc(fptr); 
    } 

我在 fopen 中遇到错误。

标签: c

解决方案


您正在使用strtok_r-internal 数据项,实际上不应使用它,而只是在对strtok_r.

command = strtok(buf," ");
if (command) {
   ....

反而。


推荐阅读