'忽略fgets的返回值'在C聊天客户端程序中

发布于 2025-01-23 20:03:34 字数 3951 浏览 3 评论 0原文

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <errno.h>

#define MAX_CLIENTS 100
#define BUFFER_SZ 2048
#define NAME_LEN 32

volatile sig_atomic_t flag = 0;
int sockfd = 0;
char name[NAME_LEN];

void str_overwrite_stdout(){
    printf("\r%s", "> ");
    fflush(stdout);
}

void str_trim_lf(char* arr, int length){
    for(int i = 0; i < length; i++) {
        if(arr[i] == '\n'){
            arr[i] = '\0';
            break;
        }
    }
}

void catch_ctrl_c_and_exit(){
    flag = 1;
}

void recv_msg_handler(){
    char message[BUFFER_SZ] = {};
    while(1){
        int receive = recv(sockfd, message, BUFFER_SZ, 0);
        if(receive > 0) {
            printf("%s", message);
            str_overwrite_stdout();
        } else if (receive == 0) {
            break;
        }
        bzero(message, BUFFER_SZ);
    }
}

void send_msg_handler(){
    char buffer[BUFFER_SZ] = {};
    char message[BUFFER_SZ + NAME_LEN] = {};

    while(1) {
        str_overwrite_stdout();
        fgets(buffer, BUFFER_SZ, stdin);
        str_trim_lf(buffer, BUFFER_SZ);

        if(strcmp(buffer, "exit") == 0) {
            break;
        } else {
            sprintf(message, "%s: %s\n", name, buffer);
            send(sockfd, message, strlen(message), 0);
        }

        bzero(buffer, BUFFER_SZ);
        bzero(message, BUFFER_SZ + NAME_LEN);
    }
    catch_ctrl_c_and_exit(2);
}

int main(int argc, char **argv) {
    if(argc!=2) {
        printf("usage: %s <port> \n", argv[0]);
        return EXIT_FAILURE;
    }

    char *ip = "127.0.0.1";
    int port = atoi(argv[1]);

    signal(SIGINT, catch_ctrl_c_and_exit);
    
    printf("Enter name: ");
    fgets(name, NAME_LEN, stdin);
    str_trim_lf(name, strlen(name));

    if(strlen(name) > NAME_LEN - 1 || strlen(name) < 2){
        printf("Enter your name correctly!\n");
        return EXIT_FAILURE;
    } 

    struct sockaddr_in server_addr;

    //socket settings
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(ip);
    server_addr.sin_port = htons(port);

    //connect to server
    int err = connect(sockfd,(struct sockaddr*)&server_addr, sizeof(server_addr));
    if (err == -1){
        printf("ERROR: UNABLE TO CONNECT");
        return EXIT_FAILURE;
    }

    //send name

    send(sockfd, name, NAME_LEN, 0);
    printf("CHATROOM PROGRAM STARTED\n\n\n");

    pthread_t send_msg_thread;
    if(pthread_create(&send_msg_thread, NULL, (void*)send_msg_handler, NULL) != 0){
        printf("ERROR: PTHREAD ERR\n");
        return EXIT_FAILURE;
    }

    pthread_t recv_msg_thread;
    if(pthread_create(&recv_msg_thread, NULL, (void*)recv_msg_handler, NULL) != 0){
        printf("ERROR: PTHREAD ERR\n");
        return EXIT_FAILURE;
    }
    while(1){
        if(flag){
            printf("\nGoodbye\n");
            break;
        }
    }
    close(sockfd);

    
    return EXIT_SUCCESS;
}

这是我客户端程序的代码。我目前正在使用Server.c和client.c进行聊天室项目。它应该由多线程服务器和客户端组成。我无法弄清楚为什么我在编译时会遇到这些错误。知道为什么会说他们没有使用?

client.c: In function ‘send_msg_handler’:
client.c:59:3: warning: ignoring return value of ‘fgets’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   59 |   fgets(buffer, BUFFER_SZ, stdin);
      |   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
client.c: In function ‘main’:
client.c:87:2: warning: ignoring return value of ‘fgets’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   87 |  fgets(name, NAME_LEN, stdin);
      |  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

来自此图像

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <errno.h>

#define MAX_CLIENTS 100
#define BUFFER_SZ 2048
#define NAME_LEN 32

volatile sig_atomic_t flag = 0;
int sockfd = 0;
char name[NAME_LEN];

void str_overwrite_stdout(){
    printf("\r%s", "> ");
    fflush(stdout);
}

void str_trim_lf(char* arr, int length){
    for(int i = 0; i < length; i++) {
        if(arr[i] == '\n'){
            arr[i] = '\0';
            break;
        }
    }
}

void catch_ctrl_c_and_exit(){
    flag = 1;
}

void recv_msg_handler(){
    char message[BUFFER_SZ] = {};
    while(1){
        int receive = recv(sockfd, message, BUFFER_SZ, 0);
        if(receive > 0) {
            printf("%s", message);
            str_overwrite_stdout();
        } else if (receive == 0) {
            break;
        }
        bzero(message, BUFFER_SZ);
    }
}

void send_msg_handler(){
    char buffer[BUFFER_SZ] = {};
    char message[BUFFER_SZ + NAME_LEN] = {};

    while(1) {
        str_overwrite_stdout();
        fgets(buffer, BUFFER_SZ, stdin);
        str_trim_lf(buffer, BUFFER_SZ);

        if(strcmp(buffer, "exit") == 0) {
            break;
        } else {
            sprintf(message, "%s: %s\n", name, buffer);
            send(sockfd, message, strlen(message), 0);
        }

        bzero(buffer, BUFFER_SZ);
        bzero(message, BUFFER_SZ + NAME_LEN);
    }
    catch_ctrl_c_and_exit(2);
}

int main(int argc, char **argv) {
    if(argc!=2) {
        printf("usage: %s <port> \n", argv[0]);
        return EXIT_FAILURE;
    }

    char *ip = "127.0.0.1";
    int port = atoi(argv[1]);

    signal(SIGINT, catch_ctrl_c_and_exit);
    
    printf("Enter name: ");
    fgets(name, NAME_LEN, stdin);
    str_trim_lf(name, strlen(name));

    if(strlen(name) > NAME_LEN - 1 || strlen(name) < 2){
        printf("Enter your name correctly!\n");
        return EXIT_FAILURE;
    } 

    struct sockaddr_in server_addr;

    //socket settings
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(ip);
    server_addr.sin_port = htons(port);

    //connect to server
    int err = connect(sockfd,(struct sockaddr*)&server_addr, sizeof(server_addr));
    if (err == -1){
        printf("ERROR: UNABLE TO CONNECT");
        return EXIT_FAILURE;
    }

    //send name

    send(sockfd, name, NAME_LEN, 0);
    printf("CHATROOM PROGRAM STARTED\n\n\n");

    pthread_t send_msg_thread;
    if(pthread_create(&send_msg_thread, NULL, (void*)send_msg_handler, NULL) != 0){
        printf("ERROR: PTHREAD ERR\n");
        return EXIT_FAILURE;
    }

    pthread_t recv_msg_thread;
    if(pthread_create(&recv_msg_thread, NULL, (void*)recv_msg_handler, NULL) != 0){
        printf("ERROR: PTHREAD ERR\n");
        return EXIT_FAILURE;
    }
    while(1){
        if(flag){
            printf("\nGoodbye\n");
            break;
        }
    }
    close(sockfd);

    
    return EXIT_SUCCESS;
}

This is the code for my client.c program. I am currently working on a Chatroom project with a server.c and a client.c. It is supposed to consist of a multithreaded server and a client. I cannot figure out why I am getting these errors when compiling. Any idea why it would be saying they are unused?

client.c: In function ‘send_msg_handler’:
client.c:59:3: warning: ignoring return value of ‘fgets’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   59 |   fgets(buffer, BUFFER_SZ, stdin);
      |   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
client.c: In function ‘main’:
client.c:87:2: warning: ignoring return value of ‘fgets’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   87 |  fgets(name, NAME_LEN, stdin);
      |  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

From this image

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

是你 2025-01-30 20:03:34

知道为什么会说他们没有使用?

那是因为他们没有使用。

警告(不是错误)是关于fgets调用的返回值,您完全忽略了。 fgets返回类型char *的值,并且该返回值带有有关呼叫成功或失败的信息。具体来说,如果发生错误或到达文件的末尾,则返回零指针,而无需读取任何字符。

如果您不认识和处理这种情况,那么您的程序在发生时可能会表现出较差的行为(他们会)。因此,例如,

有缺陷:

  fgets(name,name_len,stdin);
 

更好的:

    if (fgets(name, NAME_LEN, stdin) == NULL) {
        // handle EOF / error ...
    }

Any idea why it would be saying they are unused?

That would be because they are unused.

The warnings (not errors) are about the return value of the fgets calls, which you are altogether ignoring. fgets returns a value of type char *, and that return value carries information about the success or failure of the call. Specifically, it returns a null pointer if an error occurs or if the end of the file is reached without any more characters being read.

If you do not recognize and handle such situations then your program is likely to exhibit poor behavior when they occur (and they will). So, for example,

FLAWED:

    fgets(name, NAME_LEN, stdin);

BETTER:

    if (fgets(name, NAME_LEN, stdin) == NULL) {
        // handle EOF / error ...
    }
眉黛浅 2025-01-30 20:03:34

我无法弄清楚为什么我在编译时会遇到这些错误。

你不是。正如它所说,他们是警告,而不是错误。

知道为什么会说他们没有使用?

因为他们没有使用。您忽略fgets的返回值。这几乎从来都不是正确的事情,因为您不知道该操作是成功还是失败。

I cannot figure out why I am getting these errors when compiling.

You aren't. As it says, they're warnings, not errors.

Any idea why it would be saying they are unused?

Because they are unused. You ignore the return value of fgets. That's almost never the right thing to do because you have no idea whether the operation succeeded or failed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文