将输入存储到数组中的宏(C)

时间:2017-09-13 13:43:46

标签: c arrays macros

我已经定义了一个宏,如下所示。

bool DownloadManager::saveToDisk(const QString &filename, QIODevice *data)
{
    LogManager* logmgr = LogManager::GetInstance();
    FileManager* filemgr = FileManager::GetInstance();

    QFileInfo fileinfo(filename);
    QString dirpath = fileinfo.absoluteDir().absolutePath();

    if (!filemgr->DirectoryIsPresent(dirpath))
    {
        if (!filemgr->CreateDirectory(dirpath)) {
            logmgr->Log(LOG_LEVEL_ERROR, QString("cannot create directory (") + dirpath + ")");
        }
    }

    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly)) {
        const QString errorText = QString("Could not open ") + filename + QString(" for writing:") + file.errorString();
        logmgr->Log(LOG_LEVEL_ERROR, errorText);
        return false;
    }

    file.write(data->readAll());
    file.close();

    return true;
}

void DownloadManager::downloadFinished(QNetworkReply *reply)
{
    LogManager* logmgr = LogManager::GetInstance();

    if (m_currentDownloads.contains(reply))
    {
        QUrl url = reply->url();
        if (reply->error() != QNetworkReply::NoError) {
            m_nbFailedDownload++;
            const QString errorText = QString("Download of ")+ url.toString() +" failed: " + reply->errorString() + " (" + QString::number(reply->error()) + ")";
            logmgr->Log(LOG_LEVEL_ERROR, errorText);
        } else {
            m_nbSucceededDownload++;
            QString filename = saveFileName(url);
            if (saveToDisk(filename, reply))
            {
                const QString infoText = QString("Download of ") + url.toString() + " succeeded (saved to " + filename + ")";
                logmgr->Log(LOG_LEVEL_INFO, infoText);
            }
        }

        m_currentDownloads.removeAll(reply);
        reply->deleteLater();
    }

    int total = m_nbTotalDownload == 0? 1:m_nbTotalDownload;
    emit onProgress((m_nbFailedDownload + m_nbSucceededDownload) * 100 / total);


    if (m_currentDownloads.isEmpty()){
        logmgr->Log(LOG_LEVEL_INFO, "DownloadManager downloads finished");
        emit onFinished();
    }
}

我想使用我在表/数组中定义的名称来迭代这个宏。可以这样做吗?如果是这样,我该怎么做?

注意:以上示例仅用于说明目的:)

1 个答案:

答案 0 :(得分:0)

您所询问的内容并不完全清楚,但听起来很像您正在寻找“X宏”模式:

#include <stdio.h>

// list of data
#define NAME_LIST \
  X(foo)          \
  X(bar)          \
  X(hello)        \
  X(world)


// whatever you are actually using these for, maybe an enum or variable names?
typedef enum  
{
  // temporarily define the meaning of "X" for all data in the list:
  #define X(name) PRE_##name##_POST,
    NAME_LIST
  #undef X // always undef when done
} whatever_t;


// helper macro to print the name of the enum    
#define STRINGIFY(str) #str


int main()
{
  #define X(name) printf("%s %d\n", STRINGIFY(PRE_##name##_POST), PRE_##name##_POST);
    NAME_LIST
  #undef X
}

输出:

PRE_foo_POST 0
PRE_bar_POST 1
PRE_hello_POST 2
PRE_world_POST 3