This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
这是一段测试名为“ logf”的函数的代码,该函数接受两个参数,并使用它们记录一些信息。在这种情况下,函数的第一个参数是要记录的字符串,第二个参数是在文件系统中保存日志文件路径的字符串。第一个字符串(带有时间戳)被打印到stdout和日志文件中。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

typedef struct tm tm;

int logf(char input_string[], char log_file_string[])
{
    /*Initializations.*/
    char output_string[32767];
    FILE* log_file_stream;
    time_t current_time_epoch_format;
    tm* current_time_calandar_format;

    /*Creating timestamp in output string, amending first argument to output string, and logging.*/
    if ((strlen(input_string) + 23) > 32767) return EXIT_FAILURE;
    if ((current_time_epoch_format = time(&current_time_epoch_format)) == -1) return EXIT_FAILURE;
    if ((current_time_calandar_format = localtime(&current_time_epoch_format)) == NULL) return EXIT_FAILURE;
    if (strftime(output_string, 23, "[%d-%m-%Y %H:%M:%S] ", current_time_calandar_format) != 22) return EXIT_FAILURE;
    if ((log_file_stream = fopen(log_file_string, "a")) == NULL) return EXIT_FAILURE;
    if (printf("%s\n", strcat(output_string, input_string)) < 1) return EXIT_FAILURE;
    if (fprintf(log_file_stream, "%s\n", output_string) < 1) return EXIT_FAILURE;
    if (fclose(log_file_stream) == EOF) return EXIT_FAILURE;
    return EXIT_SUCCESS;
}

int main(int argc, char** argv)
{
    /*Initializations.*/
    int EXIT_CODE;

    /*Print the returned integer from logf and exit.*/
    printf("%d\n", (EXIT_CODE = logf(argv[1], argv[2])));
    exit(EXIT_CODE);
}

最佳答案

该程序调用未定义的行为,因为名称logf保留供外部使用。这是标准数学函数之一的名称。是否由于我未检查的其他原因而调用了未定义的行为。

关于c - 此代码是否包含未定义的行为或隐藏的错误?我错过了什么? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13897315/

10-15 05:12