我正在编写用作生成和输出 gif 图像的 cgi 的 C 程序。它们用在带有 form 标签的 HTML 页面中
<img src="/cgi-bin/gifprogram.cgi?param=val&etc">,其中查询字符串参数描述了由 cgi 生成的图像。
像这样调用的 C 程序 cgi 将它们的输出发送到 stdout。在这种情况下,输出是一个包含大量二进制(不可打印)字节的 gif 图像。这已经在 Unix/Linux 上运行良好。但是 Windows 显然需要一个单独的非便携式_setmode(_fileno(stdout),_O_BINARY)调用(和一些特定于 Windows 的调用#include)。否则,您会遇到常见的 cr/lf 问题,即每个 0x0A 前面都有一个虚假的 0x0D。这在 gif 中看起来不太好 :(
是否有任何可移植的方法来解决这个问题,使用 ANSI 标准 C 没有任何特定于平台的语法,并且没有很多#ifdef东西来尝试检测 Windows 编译环境?此外,一些 Windows 编译器显然使用,_setmode(_fileno(stdout),_O_BINARY)而其他编译器使用setmode(fileno(stdout),O_BINARY),我也必须尝试检测。
>>编辑<<回复评论...
谢谢你们。显然,我将不得不采用一些完全符合 posix 兼容/便携式的程序,并且只为 Windows [nb,JoNaThAn:真的,不需要编辑以大写:),--我的个人写作风格是故意的语法松散]。
下面是我正在考虑引入的一些愚蠢之处的第一次剪辑。据我所知,使用 mingw 似乎有效。它是否足够,即适用于所有或大多数其他编译器?是否有必要,即用更少/更易读的代码行来完成同样的事情的任何简短而整洁/快速和肮脏的方式?
/* ---
* windows-specific header info
* ---------------------------- */
#ifndef WINDOWS /* -DWINDOWS …Run Code Online (Sandbox Code Playgroud) 我正在使用的方式只是尝试fopen()要检查的文件,
/* --- does file exist??? --- */
char fname[999] = "whatever"; /* constructed during execution */
FILE *fp = NULL; /* try to fopen(fname,"r") */
int isfilefound = 0; /* set true if fopen() succeeds */
if ( (fp = fopen(fname,"r")) /* try to fopen() for read */
!= NULL ) { /* succeeded */
isfilefound = 1; /* set file found flag */
fclose(fp); } /* and just close the file */
Run Code Online (Sandbox Code Playgroud)
是否有更快,更少资源的方式?... unix/linux的特定方式?一种Windows方式?并且最好是便携式posix兼容方式(如上所述)?它已经完成了很多次(1000次),所以我不希望没有任何理由不必要地打开和关闭文件.
-------------------------------------------------- ---------------
编辑好的,根据下面的答案,我把以下的小函数放在一起,用于检查文件(已经:)是否存在于posix,windows,其他便携式办法... …
malloc / calloc显然使用交换空间来满足超出可用空闲内存的请求。随着磁盘使用指示灯持续亮起,这几乎使系统挂起。在发生这种情况之后,我还不确定为什么,我编写了以下5行测试程序来检查这确实是系统挂起的原因,
/* --- test how many bytes can be malloc'ed successfully --- */
#include <stdio.h>
#include <stdlib.h>
int main ( int argc, char *argv[] ) {
unsigned int nmalloc = (argc>1? atoi(argv[1]) : 10000000 ),
size = (argc>2? atoi(argv[2]) : (0) );
unsigned char *pmalloc = (size>0? calloc(nmalloc,size):malloc(nmalloc));
fprintf( stdout," %s malloc'ed %d elements of %d bytes each.\n",
(pmalloc==NULL? "UNsuccessfully" : "Successfully"),
nmalloc, (size>0?size:1) );
if ( pmalloc != NULL ) free(pmalloc);
} /* --- end-of-function main() --- …Run Code Online (Sandbox Code Playgroud)