比较c中的两个字符串

时间:2012-02-25 11:10:16

标签: c

我对C中的字符串和字符数组有一个基本的问题。

下面我有一些基本代码,用于比较通过套接字(telnet)传输的数据和现有字符串。然而,这失败了。如果我比较char数组中的一个字符,它在[1] == out [1]中工作。 你能告诉为什么字符串不匹配,如果我遗失了什么。我是否需要将char转换为anther类型的字符串?

THX 领域

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void dostuff(int); /* function prototype */
void error(const char *msg)
{
perror(msg);
exit(1);
}

int main(int argc, char *argv[])
{
 int sockfd, newsockfd, portno, pid;
 socklen_t clilen;
 struct sockaddr_in serv_addr, cli_addr;

 if (argc < 2) {
     fprintf(stderr,"ERROR, no port provided\n");
     exit(1);
 }
 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 if (sockfd < 0)
    error("ERROR opening socket");
 bzero((char *) &serv_addr, sizeof(serv_addr));
 portno = atoi(argv[1]);
 serv_addr.sin_family = AF_INET;
 serv_addr.sin_addr.s_addr = INADDR_ANY;
 serv_addr.sin_port = htons(portno);
 if (bind(sockfd, (struct sockaddr *) &serv_addr,
          sizeof(serv_addr)) < 0)
          error("ERROR on binding");
 listen(sockfd,5);
 clilen = sizeof(cli_addr);
 while (1) {
     newsockfd = accept(sockfd,
           (struct sockaddr *) &cli_addr, &clilen);
     if (newsockfd < 0)
         error("ERROR on accept");
     pid = fork();
     if (pid < 0)
         error("ERROR on fork");
     if (pid == 0)  {
         close(sockfd);
         dostuff(newsockfd);
         exit(0);
     }
     else close(newsockfd);
 } /* end of while */
 close(sockfd);
 return 0; /* we never get here */
 }

/******** DOSTUFF() *********************
 There is a separate instance of this function
for each connection.  It handles all communication
 once a connnection has been established.
*****************************************/
void dostuff (int sock)
{
int n;
char buffer[2];
char kjh[] = "aaa";

bzero(buffer,256);
n = read(sock,buffer,255);
if (n < 0) error("ERROR reading from socket");
if (strcmp(ptr,kjh) == 0)
{ 
 printf("they are the same: %s.\n",buffer);
 do_other_stuff();
}
printf("Here is the message!: %s\n",buffer);
n = write(sock,"I got your message",19);
if (n < 0) error("ERROR writing to socket");
}

void do_other_stuff()
{
printf("function works:");
}

2 个答案:

答案 0 :(得分:1)

首先,缓冲区只有2个字符长,但read(sock, buffer, 255)尝试阅读的内容远不止于此。此外,您需要在执行strcmp

之前在字符串末尾添加空字符

答案 1 :(得分:0)

唯一可以使这段代码工作的是拥有良好的基础知识,你在这里犯下愚蠢的错误,观察并预测你可能会变得懒惰的区域,比如在指针和字符串操作中。从长远来看会对你有所帮助。