自测之Lesson5:标准I/O

题目:使用perror函数和strerror函数编写一个程序。

 

程序代码:

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

int main()
{
        FILE *fp = fopen("file.txt", "r");
        if (fp == NULL) {
                perror("ERROR");    // 返回上一个系统调用的错误原因,此原因依照全局变量errno的值来决定要输出的字符串
                printf("strerror:%s\n", strerror(errno));
                return -1;
        }
        fclose(fp);
        return 0;
}

 

 

 

题目:编写带可变参数的WriteLog函数。

 

程序代码:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>

int WriteLog(char *pFmt, ...)
{
        va_list args;
        char szBuf[256];
        va_start(args, pFmt);
        vsnprintf(szBuf, 255, pFmt, args);
        va_end(args);
        FILE *pf = fopen("test", "w");
        if (pf == NULL)
        {
                perror("ERROR");
                return -1;
        }
        fprintf(pf, "%s\r\n", szBuf);
//      fwrite(szBuf, sizeof(char), sizeof(szBuf), pf);
        fclose(pf);
        return 0;
}

int main()
{
        WriteLog("Hello %s, %d, %s\n", "World", 2018, "upup");
        return 0;
}

 

  

 

posted @ 2018-03-04 23:38  GGBeng  阅读(198)  评论(0编辑  收藏  举报