可变参数例子

来源:互联网 发布:ubuntu无法启动chrome 编辑:程序博客网 时间:2024/06/05 11:57

// a1.h:

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <iostream>


#define BUFFER_SIZE 1024

int comm_PrintToCsv(FILE *fp,int inum, char* pszarg, ...);

 

 

 // a1.cpp : コンソール アプリケーション用のエントリ ポイントの定義
//
extern “C”
#include "stdafx.h"
#include "a1.h"

int main(void)
{
    // file point
    FILE * fp;
    // open file
    if((fp = fopen("C://test.csv","a+"))==NULL)
    {
        printf("can not open/n");
        exit(1);
    }
    int a = comm_PrintToCsv(fp, 3, "aab","bbs","ssd");
    int b = comm_PrintToCsv(fp,5,"saa","bbdgas","asga","111111","44444");
    // close file
    if (fp)
    {
        fclose(fp);
        fp = NULL;
    }
    if (logP)
    {
        fclose(logP);
        logP = NULL;
    }
    return 0;
}

/*  */
int comm_PrintToCsv(FILE *fp, int num, char* arg, ...)
{
    // number error
    if(num < 1) return 0;

    va_list ap;
    int n = num;
    // output stringbuffer
    char pszOut[BUFFER_SIZE];
    memset(pszOut, 0x00, BUFFER_SIZE);
    // get parameter list
    va_start(ap, arg);
    // make output stringbuffer header
    sprintf(pszOut, "/"%s/"", arg);

    // make outout stringbuffer from parameter list
    while(--n > 0)
    {
       sprintf(pszOut, "%s,/"%s/"", pszOut, va_arg(ap,char *));        
    }

    va_end(ap);
    // output to file
    fputs(pszOut, fp);
    fputs("/n", fp);
    return 0;
}

原创粉丝点击