[英]How can I print the current date and time and a string to one line in a file in C?
[英]How can i print current time when string is "Time" in C?
我正在開發一個 c 程序,該程序發送消息並從服務器獲取消息,但如果字符串是“時間”,我想將時間發送給 EchoClient。 我該怎么做?
我曾嘗試使用一些代碼,但對於我的知識來說它們似乎太復雜了。有人知道該怎么做嗎? EchoClient.c
#include "nethelp.h"
int main(int argc, char **argv)
{
int clientfd, port;
char *host, buf[MAXLINE];
int n;
if (argc != 3) {
fprintf(stderr, "usage: %s <host> <port>\n", argv[0]);
exit(0);
}
host = argv[1];
port = atoi(argv[2]);
clientfd = open_clientfd(host, port);
while (fgets(buf, MAXLINE, stdin) != NULL) {
write(clientfd, buf, strlen(buf));
n = readline(clientfd, buf, MAXLINE);
write(1, buf, n);
}
close(clientfd);
exit(0);
}
EchoServer.c
#include "nethelp.h"
void echo(int connfd);
void *thread(void *vargp);
int main(int argc, char **argv)
{
int listenfd, *connfdp, port, clientlen=sizeof(struct sockaddr_in);
struct sockaddr_in clientaddr;
pthread_t tid;
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(0);
}
port = atoi(argv[1]);
listenfd = open_listenfd(port);
while (1) {
connfdp = malloc(sizeof(int));
*connfdp = accept(listenfd, (struct sockaddr*)&clientaddr, &clientlen);
pthread_create(&tid, NULL, thread, connfdp);
}
}
void * thread(void * vargp)
{
int connfd = *((int *)vargp);
pthread_detach(pthread_self());
free(vargp);
echo(connfd);
close(connfd);
return NULL;
}
void echo(int connfd)
{
size_t n;
char buf[MAXLINE];
while((n = readline(connfd, buf, MAXLINE)) != 0) {
printf("server received %d bytes\n", n);
write(connfd, buf, n);
}
}
要將當前時間作為文本發送,
if (strcmp(buf, "time")== 0) {
time_t now;
time(&now); // Get the current time
if (now == -1) Handle_Error();
struct tm *tm;
tm = gmtime(&now); // Convert to a time struct (YMD HMS etc.) as if Universal time
if (tm == NULL) Handle_Error();
char buf[100];
// See strftime and ISO 8601 for format details
// Convert from a time struct to a string
if (strftime(buf, sizeof buf, "%FT%T") == 0) Handle_Error();
send(buf);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.