【发布时间】:2018-12-14 10:27:47
【问题描述】:
我目前正在尝试使用strcat 在我的服务器程序中连续连接多个“字符串”。
相关部分代码如下:
我成功拿到了客户端发来的年月日文件名,因为打印的很好。
我的字符串初始化如下:
char username[MAX_USERNAME_SIZE];
char filename[MAX_FILENAME_SIZE];
char path[MAX_FILEPATH_SIZE];
char buff[BUFFSIZE];
char year[4], month[2], day[2];
...
if ((numbytes = recv(new_fd, &username, MAX_USERNAME_SIZE, 0)) == -1)
{
perror("Serveur: recv username");
return EXIT_FAILURE;
}
username[numbytes] = '\0';
printf("Serveur: username: %s\n", username);
/* create user's repository if it doesn't exist yet*/
// 3) get date from client
if ((numbytes = recv(new_fd, year, 4, 0)) == -1)
{
perror("Serveur: recv year");
return EXIT_FAILURE;
}
year[numbytes] = '\0';
printf("year: %s\n", year);
if ((numbytes = recv(new_fd, month, 2, 0)) == -1)
{
perror("Serveur: recv month");
return EXIT_FAILURE;
}
month[numbytes] = '\0';
printf("month: %s\n", month);
if ((numbytes = recv(new_fd, day, 2, 0)) == -1)
{
perror("Serveur: recv day");
return EXIT_FAILURE;
}
day[numbytes] = '\0';
printf("day: %s\n", day);
// get filename from client
if ((numbytes = recv(new_fd, filename, MAX_FILENAME_SIZE, 0)) == -1)
{
perror("Serveur: recv filename");
return EXIT_FAILURE;
}
filename[numbytes] = '\0';
printf("Serveur: filename: %s\n", filename);
但是当我尝试正确连接所有字符串时遇到问题。
// create user repository
strcpy(path, argv[1]);
printf("Serveur: Path: %s\n", path);
strcat(path, "/");
printf("Serveur: Path: %s\n", path);
strcat(path, username);
strcat(path, "/");
printf("Serveur: Path: %s\n, username:%s\n", path, username);
my_mkdir(path, MODE);
strcat(path, year);
strcat(path, "/");
printf("Serveur: Path: %s\n, year: %s\n", path, year);
my_mkdir(path, MODE);
strcat(path, month);
strcat(path, "/");
printf("Serveur: Path: %s\n, month: %s\n", path, month);
my_mkdir(path, MODE);
strcat(path, day);
strcat(path, "/");
printf("Serveur: Path: %s\n, day: %s\n", path, day);
my_mkdir(path, MODE);
strcat(path, filename);
}
在我这样做之后,用户名、年份和月份的打印效果令人惊讶。 这是我执行代码时的输出(我确定文件名是可以的,因为我从客户端检索的文件保存在正确的名称下):
Serveur: connection recieved from client 127.0.0.1
Serveur: username: student
year: 95
month: 5
day: 11
Serveur: filename: tux.png
Serveur: Path: ./Test0/Test1
Serveur: Path: ./Test0/Test1/
Serveur: Path: ./Test0/Test1//
, username:
Serveur: Path: ./Test0/Test1///
, year:
Serveur: Path: ./Test0/Test1////
, month:
Serveur: Path: ./Test0/Test1////11/
, day: 11
我真的很想清楚我错在哪里。提前致谢
【问题讨论】:
-
您最喜欢的调试器将在这里为您提供帮助。如果你提供一个minimal reproducible example(这意味着一个没有
recv东西的带有测试数据的独立程序),我们可以提供帮助,但是这样做,你可能会自己发现错误。 -
你没有告诉我们
path是如何定义的,所以那里很容易出现问题 -
该错误存在于您未发布的某些代码中。两个代码块之间执行什么代码?顺便说一句:
recv(new_fd, &username,...我猜你不知道&。 -
你的缓冲区是如何定义的?
char username[??.... -
@ChrisTurner 当我在客户端和服务器程序中将年、月和日的大小分别更改为 5、3、3 并删除每个“var[numbytes] =”时,我达到了预期的结果\0' ´(其中 var = {年、月或日})在服务器程序中。但是,我仍然不明白为什么。这也意味着我正在从客户端向服务器发送“\0”。这不是多余的吗?