c - 解析命令并将文件路径传递给 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 中遇到错误。
解决方案
您正在使用strtok_r
-internal 数据项,实际上不应使用它,而只是在对strtok_r
.
写
command = strtok(buf," ");
if (command) {
....
反而。
推荐阅读
- python - 如何将条件指令块简化为 python 应用程序中的一个 elif 语句?
- json - 如何获取 PSCustom 对象的长度?
- sdk - 如何将 do_populate_sdk 任务添加到 avro-c BitBake 配方?
- sql-server - 如何在 SQL 中实现 PIVOT?
- c# - 用于 DBContext 的 Azure KeyVault:“没有为此 DbContext 配置数据库提供程序”
- wordpress - Mailgun 无法向域名注册商拥有的地址发送电子邮件
- c# - 如何在 lambda 函数中按部分将存档流式传输到 S3?
- google-chrome-devtools - 预览版 chrome-devtools 中的 Base 64。怎么修?
- awk - awk 字符串大于变量
- c# - 如何在不进行任何压缩的情况下保存位图文件