ITeye博客

如何用CGI(C/C++)输出二进制内容

meiping · 2011-02-22 22:12 · C/C++ · 编程语言 · C · C++ · C# · CGI · Excel · Markdown

用CGI输出文本文件已是司空见惯,输出二进制呢?你尝试过吗?

下面的代码演示在linux下想浏览器输出Excel文件

tt.cpp

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "stdio.h"
 
int main(int argc, char** argv)
{       
    // 输出Header
    char* header = "Content-Type: application/vnd.ms-excel\r\n"
                 "Content-Disposition: attachment; filename=\"support.xls\"\r\n"
                 "Expires: 0\r\n"
                 "Cache-Control: must-revalidate, post-check=0,pre-check=0\r\n"
                 "Pragma: public\r\n\r\n" ;
write(STDOUT_FILENO, header, strlen(header));
 
    int xls = open("array.xls", O_RDONLY);
    char buf[1024];
 
    size_t num;
    while ((num = read(xls, buf, 1024)) > 0)
    {
       write(STDOUT_FILENO, buf, num);
    }
    close(xls);
    return 0;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。