---
title: "如何用CGI(C/C++)输出二进制内容"
author: "meiping"
date: "2011-02-22T22:12:22Z"
tags: ["C", "C#", "C++", "CGI", "Excel"]
categories: ["编程语言"]
slug: "cgi-c-c"
draft: false
lastmod: "2011-02-22T22:36:17Z"
id: 918818
url: "https://meiping.iteye.com/blog/918818"
---

用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;
}
```