如何使用C中的错误处理代码访问并行结构值

时间:2018-05-03 02:20:18

标签: c struct error-handling

我正在学习C编程,我看到了这篇文章。

C naming suggestion for Error Code enums

我尝试编写以下代码,但我不知道如何通过我指定的错误代码访问结构字符串。下面是我的代码,请忽略未使用的变量。请帮帮我谢谢。

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


/*  ASCII Value Definitions */
#define ASCII_NULL 0x00
#define ASCII_HT 0x09
#define ASCII_NL 0x0A
#define ASCII_CR 0x0D
#define ASCII_SP 0x20
#define ASCII_HASHTAG 0x23


#define COLOR_COMPONENTS 3


enum _error_definition {
    E_SUCCESS = 0,
    E_INPUT_FILE_ERROR = -1,
    E_OUTPUT_FILE_ERROR = -2,
    E_INVALID_FORMAT = -3,
    E_INVALID_DIMENSIONS = -4,
    E_ALLOCATION_ERROR = -5,
    E_FILE_READ_ERROR = -6,
    E_FILE_WRITE_ERROR = -7
};

/* type to provide in your API */
typedef _error_definition error_t;

struct _errordesc {
    int code;
    char *message;
} errordesc[] = {
    {E_SUCCESS, "No Error\n"},
    {E_INPUT_FILE_ERROR, "Error: Invalid input file\n"},
    {E_OUTPUT_FILE_ERROR, "Error: Invalid output file\n"},
    {E_INVALID_FORMAT, "Error: Invalid file format\n"},
    {E_INVALID_DIMENSIONS, "Error: Invalid dimensions\n"},
    {E_ALLOCATION_ERROR, "Error in allocating image buffer\n"},
    {E_FILE_READ_ERROR, "Error in reading the image data\n"},
    {E_FILE_WRITE_ERROR, "Error in writing to file\n"}
};

void cleanUpBeforeExit(FILE *inputFile, FILE *outputFile, char *fileBuf, int error)
{
    printf(errordesc[error].message);
    if(inputFile) fclose(inputFile);
    if(outputFile) fclose(outputFile);
    if(fileBuf) free(fileBuf);
    //exit(errordesc[error].code);
}

int main(int argc, char *argv[])
{
    FILE            *infp = ASCII_NULL;
    FILE            *outfp = ASCII_NULL;
    char            outfname[256];
    int             err;
    int             datasize; 
    int             num;
    int             x;
    int             y;
    char            *datap = ASCII_NULL;
    unsigned char   pixel[3];   // R, G, B
    int             para[3];
    unsigned char   *p;
    char            magic[10];

    cleanUpBeforeExit(infp, outfp, datap, E_OUTPUT_FILE_ERROR);
    getchar();

}

1 个答案:

答案 0 :(得分:0)

由于errordesc[]元素的定义方式,您可以使用code元素errordesc成员的否定值作为{{1}的索引}}数组来访问结构变量的errordesc部分。

例如,函数message中的代码error

cleanUpBeforeExit()

而不是

printf("\n%s", errordesc[-error].message);

前者将打印

printf(errordesc[error].message);