我正在製作一個聊天程序,它使用recv
和send
通過套接字發送和接收信息。現在我正在嘗試添加一個函數,以便它自動將chatlog保存到文件中。我現在所擁有的只是打開/創建文件,但不會寫入任何內容。無法將字符串保存到log.txt
在第46行,它打印「收到的消息」,並在聊天中打印「自己的消息」。任何人都能發現我的錯誤?
int ThereAndBackAgain(SOCKET *clientSocket){
char keyPress ='\0',tmp[200]={0};
int index=0, i = 0;
FILE *fp;
char buffer[256];
char nickName[10] = "Sneep";
memset(&buffer[0], 0, sizeof(buffer));
fp = fopen("chatlog.txt", "a");
do{
while(!kbhit()){
if (recv(*(clientSocket), buffer, 255,0) != -1){
printf("%s: \n",nickName);
printf("%s\n", buffer); //Prints received messages
fputs(buffer, fp);
memset(&buffer[0], 0, sizeof(buffer));
i = 0;
}
}
if(keyPress=tmp[index++]=getch()){
if(keyPress == '\r'){ // if user presses enter
for(i = 0; i < strlen(buffer); i++){
if (i == 0)
printf("\b ");
else
printf("\b\b ");
}
i = 0;
//print the message to a good spot on the screen
printf("\b%s\n",buffer); // Prints own messages
send(*(clientSocket),buffer,strlen(buffer),0);
memset(&buffer[0], 0, sizeof(buffer));
}
buffer[i] = keyPress;
printf("%c", keyPress);
if(keyPress == '\b'){ // if user presses backspace
printf(" \b");
buffer[i-1] = ' ';
i--;
}
else{
i++;
}
}
}while(buffer[0] != '#');
}
小調:避免每次在循環中調用'strlen()'。 'size_t len = strlen(buffer); for(i = 0; i
chux
2014-11-01 22:26:18