如何在 C 中正确使用字符串?
Java、Python 等都毁了我。我正在尝试通过响应服务器代码来自动化 FTP 客户端:
例如:
// I know this is ugly, please bear with me
char username[25];
strcat(username, USER); //"USER "
strcat(username, usr); // "foo"
strcat(username, "\n"); // = "USER foo\n"
char password[25];
strcat(password, PASS); //"PASS "
strcat(password, pswd); //"bar"
strcat(password, "\n"); // = "PASS bar\n"
//read/write loop
while (1) {
char* responsePtr;
serverCode = readSocket(sockfd, mybuffer);
if (serverCode == 221)
break;
if (serverCode == 220)
responsePtr = &username;
if (serverCode == 331)
responsePtr = &password;
writeSocket(sockfd, responsePtr);
}
当我尝试此操作时,它适用于 USER,但我得到一些 PASS 的错误文本:
C->S: USER anonymous
S->C: 331 Please specify the password.
C->S: (??_?PASS random
任何比我更明智和更有经验的人都可以给我一些 C 字符串指点?显然这不适合我。
The likes of Java, Python, and others have ruined me. I'm trying to automate an FTP client by responding to server codes:
For example:
// I know this is ugly, please bear with me
char username[25];
strcat(username, USER); //"USER "
strcat(username, usr); // "foo"
strcat(username, "\n"); // = "USER foo\n"
char password[25];
strcat(password, PASS); //"PASS "
strcat(password, pswd); //"bar"
strcat(password, "\n"); // = "PASS bar\n"
//read/write loop
while (1) {
char* responsePtr;
serverCode = readSocket(sockfd, mybuffer);
if (serverCode == 221)
break;
if (serverCode == 220)
responsePtr = &username;
if (serverCode == 331)
responsePtr = &password;
writeSocket(sockfd, responsePtr);
}
When I try this, it works for USER, but I get some mangled text for PASS:
C->S: USER anonymous
S->C: 331 Please specify the password.
C->S: (??_?PASS random
Can anyone wiser and more experienced than myself give me some C string pointers? Clearly this isn't working out for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在连接字符串之前,您需要初始化它们。默认情况下,数组未初始化。
无论如何,您可以使用 sprintf 更轻松地创建字符串:
希望您还意识到使用固定大小的缓冲区会导致缓冲区溢出错误。为了安全起见,您应该确保防范它们。这很烦人,但这对你来说是 C:
You need to initialize your strings before you concatenate to them. Arrays are not initialized by default.
For what it's worth, you can use
sprintf
to create the strings more easily:Hopefully you also realize that using fixed size buffers is a recipe for buffer overflow bugs. For security you should make sure to guard against them. It's annoying, but that's C for you:
一些有帮助的规则。
A few rules that help.
您不应该 strcat 未初始化的数组。
尝试:
第一个。
另外,您应该使用
strncat()
而不是strcat()
来避免溢出。我认为这样做更容易:
请参阅此处的一些示例。
You shouldn't strcat an uninitialized array.
Try:
for the fist one.
Also, instead of
strcat()
you should usestrncat()
to avoid overflows.I think it's easier to do:
See here for some examples.
尝试将“\n\0”而不是仅“\n”添加到用户名和密码数组中。
Try adding "\n\0" instead of just "\n" to the username and password arrays.