我正在为一个班级的项目工作,我正在运行它几次,它工作正常。突然之间,只更改了一个正在读取的文本文件而没有其他内容,它就停止了工作。我跑了它,它只是永远地跑了。我在顶部添加了一个printf,开始看到我抱着什么。当我编译并运行printf没有激活时,没有任何反应。当注释掉我的代码的主体,编译它并运行它时,printf运行正常。我从未见过这样的事情。怎么会发生这种情况?这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char* argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
FILE *list = fopen("pwlist1.txt","r");
if (list == NULL) {
printf("File fail\n");
exit(1);
}
const size_t line_size = 30;
char* line = malloc(line_size);
char buffer[256];
strcpy(buffer,"FAILURE: ");
while (fgets(line, line_size, list) != NULL && strstr(buffer, "FAILURE:") != NULL) {
portno = 48579;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("elnux1.cs.umass.edu");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
n = write(sockfd,"bloop",strlen("bloop"));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
n = write(sockfd,"667057",strlen("667057"));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
n = write(sockfd,line,strlen(line));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
}
if (strstr(buffer, "FAILURE:") == NULL) printf("You did it! The word is: %s\n",line);
else printf("Failure.\n");
close(sockfd);
return 0;
}
pwlist1.txt的内容:
test
hi
答案 0 :(得分:0)
您描述的问题的常见原因(当您在其余代码中发表评论时printf
未输出)是stdout
未被刷新。您可以通过在printf
之后添加显式刷新来解决此问题。
fflush(stdout);
由于您的问题并不清楚哪个printf
您确实遇到了问题,因此我还会对stderr
进行评分。
fflush(stderr);