⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 faqcat38c2.html

📁 this is a mirrored site c-faq. thought might need offline
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN"><!-- This collection of hypertext pages is Copyright 1995-2005 by Steve Summit. --><!-- Content from the book "C Programming FAQs: Frequently Asked Questions" --><!-- (Addison-Wesley, 1995, ISBN 0-201-84519-9) is made available here by --><!-- permission of the author and the publisher as a service to the community. --><!-- It is intended to complement the use of the published text --><!-- and is protected by international copyright laws. --><!-- The on-line content may be accessed freely for personal use --><!-- but may not be published or retransmitted without explicit permission. --><!-- --><!-- this page built Sat Dec 24 21:47:47 2005 by faqproc version 2.7 --><!-- from source file misc0.sgml dated Sat Nov 24 13:43:27 2001 --><!-- corresponding to FAQ list version 4.0 --><html><!-- Mirrored from c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=misc by HTTrack Website Copier/3.x [XR&CO'2008], Sat, 14 Mar 2009 07:58:32 GMT --><head><base ><meta name=GENERATOR content="faqproc"><title>Miscellaneous</title></head><body bgcolor="#ffffff"><H1>20. Miscellaneous</H1><a name="multretval"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/multretval.html"><!-- qtag -->Question 20.1</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How can I returnmultiplevalues from a function?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>There are several ways of doing this.(These examples show hypotheticalpolar-to-rectangular coordinate conversion functions,which must return both an <TT>x</TT> and a <TT>y</TT> coordinate.)</p><OL><li>Passpointers toseverallocations which the function can fill in:<pre>#include &lt;math.h&gt;polar_to_rectangular(double rho, double theta,		double *xp, double *yp){	*xp = rho * cos(theta);	*yp = rho * sin(theta);}...	double x, y;	polar_to_rectangular(1., 3.14, &amp;x, &amp;y);</pre><li>Havethe function return a structurecontaining the desired values:<pre>struct xycoord { double x, y; };struct xycoordpolar_to_rectangular(double rho, double theta){	struct xycoord ret;	ret.x = rho * cos(theta);	ret.y = rho * sin(theta);	return ret;}...	struct xycoord c = polar_to_rectangular(1., 3.14);</pre><li>Use a hybrid:have the function accept a pointer to a structure,which it fills in:<pre>polar_to_rectangular(double rho, double theta,		struct xycoord *cp){	cp-&gt;x = rho * cos(theta);	cp-&gt;y = rho * sin(theta);}...	struct xycoord c;	polar_to_rectangular(1., 3.14, &amp;c);</pre>(Another example of this technique is the Unix system call <TT>stat</TT>.)<li>In a pinch,you could theoretically useglobal variables(though this is rarelya good idea).</OL><p>See alsoquestions <a href="faqcat6b6b.html?sec=struct#firstclass">2.7</a>, <a href="faqcatabdc.html?sec=ptrs#passptrinit">4.8</a>, and <a href="faqcatbafd.html?sec=malloc#retaggr">7.5a</a>.<hr><hr><hr><a name="ragged"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/ragged.html"><!-- qtag -->Question 20.2</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What's a good data structure to usefor storing lines of text?I started to usefixed-sizearrays of arrays of <TT>char</TT>,but they're just too restrictive.</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>One good way of doing this is with apointer(simulating an array)to a set of pointers(each simulating an array)of <TT>char</TT>.Thisdata structureis sometimes called a``ragged array,''and looks something like this:<blockquote>[FIGURE GOES HERE]</blockquote></p><p>You could set up the tiny array in the figure above with these simple declarations:<pre>char *a[4] = {"this", "is", "a", "test"};char **p = a;</pre>(where <TT>p</TT> is the pointer-to-pointer-to-<TT>char</TT>and <TT>a</TT> is an intermediate array used to allocate the four pointers-to-<TT>char</TT>).</p><p>To really do dynamic allocation,you'd of course have to call <TT>malloc</TT>:<pre>#include &lt;stdlib.h&gt;char **p = malloc(4 * sizeof(char *));if(p != NULL) {	p[0] = malloc(5);	p[1] = malloc(3);	p[2] = malloc(2);	p[3] = malloc(5);	if(p[0] &amp;&amp; p[1] &amp;&amp; p[2] &amp;&amp; p[3]) {		strcpy(p[0], "this");		strcpy(p[1], "is");		strcpy(p[2], "a");		strcpy(p[3], "test");	}}</pre>(Some libraries have a <TT>strdup</TT> functionwhich would streamline the inner<TT>malloc</TT> and <TT>strcpy</TT> calls.It's not Standard,but it's obviously trivial to implement something like it.)</p><p>Here is a code fragmentwhich reads an entire file into memory,using the same kind of ragged array.This code is written in terms of the<TT>agetline</TT> functionfrom question <a href="faqcatbafd.html?sec=malloc#reallocnull">7.30</a>.<pre>#include &lt;stdio.h&gt;#include &lt;stdlib.h&gt;extern char *agetline(FILE *);FILE *ifp;/* assume ifp is open on input file */char **lines = NULL;size_t nalloc = 0;size_t nlines = 0;char *p;while((p = agetline(ifp)) != NULL) {	if(nlines &gt;= nalloc) {		nalloc += 50;#ifdef SAFEREALLOC		lines = realloc(lines, nalloc * sizeof(char *));#else		if(lines == NULL)		/* in case pre-ANSI realloc */			lines = malloc(nalloc * sizeof(char *));		else	lines = realloc(lines, nalloc * sizeof(char *));#endif		if(lines == NULL) {			fprintf(stderr, "out of memory");			exit(1);		}	}	lines[nlines++] = p;}</pre>(See the comments on reallocation strategyin question <a href="faqcatbafd.html?sec=malloc#reallocnull">7.30</a>.)</p><p>See also question <a href="faqcatca65.html?sec=aryptr#dynmuldimary">6.16</a>.<hr><hr><hr><a name="argv"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/argv.html"><!-- qtag -->Question 20.3</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How can I open files mentioned on the command line,and parse option flags?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Here is a skeleton which implements a traditional Unix-style<TT>argv</TT> parse,handling option flags beginning with <TT>-</TT>,and optional filenames.(The two flags acceptedby this exampleare <TT>-a</TT> and <TT>-b</TT>;<TT>-b</TT> takes an argument.)<pre>#include &lt;stdio.h&gt;#include &lt;string.h&gt;#include &lt;errno.h&gt;main(int argc, char *argv[]){	int argi;	int aflag = 0;	char *bval = NULL;	for(argi = 1; argi &lt; argc &amp;&amp; argv[argi][0] == '-'; argi++) {		char *p;		for(p = &amp;argv[argi][1]; *p != '\0'; p++) {			switch(*p) {			case 'a':				aflag = 1;				printf("-a seen\n");				break;			case 'b':				bval = argv[++argi];				printf("-b seen (\"%s\")\n", bval);				break;			default:				fprintf(stderr,					"unknown option -%c\n", *p);			}		}	}	if(argi &gt;= argc) {		/* no filename arguments; process stdin */		printf("processing standard input\n");	} else {		/* process filename arguments */		for(; argi &lt; argc; argi++) {			FILE *ifp = fopen(argv[argi], "r");			if(ifp == NULL) {				fprintf(stderr, "can't open %s: %s\n",					argv[argi], strerror(errno));				continue;			}			printf("processing %s\n", argv[argi]);			fclose(ifp);		}	}	return 0;}</pre>(This code assumes that <TT>fopen</TT>sets <TT>errno</TT> when it fails,which is not guaranteed,but usually works,and makes error messages much more useful.See also question <a href="faqcat38c2.html?sec=misc#errno">20.4</a>.)</p><p>There are several canned functions availablefor doing command line parsing in a standard way;the most popular one is<TT>getopt</TT>(see also question <a href="faqcatccbd.html?sec=resources#sources">18.16</a>).Here is the above example,rewritten to use <TT>getopt</TT>:<pre>extern char *optarg;extern int optind;main(int argc, char *argv[]){	int aflag = 0;	char *bval = NULL;	int c;	while((c = getopt(argc, argv, "ab:")) != -1)		switch(c) {		case 'a':			aflag = 1;			printf("-a seen\n");			break;		case 'b':			bval = optarg;			printf("-b seen (\"%s\")\n", bval);			break;	}	if(optind &gt;= argc) {		/* no filename arguments; process stdin */		printf("processing standard input\n");	} else {		/* process filename arguments */		for(; optind &lt; argc; optind++) {			FILE *ifp = fopen(argv[optind], "r");			if(ifp == NULL) {				fprintf(stderr, "can't open %s: %s\n",					argv[optind], strerror(errno));				continue;			}			printf("processing %s\n", argv[optind]);			fclose(ifp);		}	}	return 0;}</pre></p><p>The examples above overlook a number of nuances:a lone``<TT>-</TT>'' is often taken to mean``read standard input'';the marker ``<TT>--</TT>'' often signifies the end of the options(proper versions of <TT>getopt</TT> do handle this);it's traditional to print a usage messagewhen a command is invoked with improper or missing arguments.</p><p>If you're wondering how <TT>argv</TT> is laid out in memory,it's actually a``ragged array'';see the picture inquestion <a href="faqcat38c2.html?sec=misc#ragged">20.2</a>.See also questions<a href="faqcate107.html?sec=charstring#stringeq">8.2</a>,<a href="faqcat1067.html?sec=lib#regex">13.7</a>,and<a href="faqcatea63.html?sec=osdep#readdir">19.20</a>.</p><p>References:K&amp;R1 Sec. 5.11 pp. 110-114<br>K&amp;R2 Sec. 5.10 pp. 114-118<br>ISO Sec. 5.1.2.2.1<br>H&amp;S Sec. 20.1 p. 416<br>PCS Sec. 5.6 pp. 81-2, Sec. 11 p. 159, pp. 339-40 Appendix F<br>Schumacher, ed.,<I>Software Solutions in C</I> Sec. 4 pp. 75-85<hr><hr><hr><a name="errno"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/errno.html"><!-- qtag -->Question 20.4</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What's the right wayto use <TT>errno</TT>?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>In general,you should detect errors by checking return values,and use <TT>errno</TT> only to distinguish among the various causes of an error,such as ``File not found''or ``Permission denied''.(Typically, you use<TT>perror</TT> or<TT>strerror</TT>to print thesediscriminatingerror messages.)It's only necessary to detect errors with <TT>errno</TT>when a function does not have a unique, unambiguous,out-of-banderror return(i.e. because all of its possible return values are valid;one example is <TT>atoi</TT>).In these cases(and in these cases only;check the documentationto be surewhethera function allows this),you can detect errors by setting <TT>errno</TT> to 0,calling the function,then testing <TT>errno</TT>.(Setting <TT>errno</TT> to 0 first is important,asno library function ever doesthat for you.)</p><p>To make error messages useful,they should include all relevant information.Besides the <TT>strerror</TT>text derived from <TT>errno</TT>,it may also be appropriate to print the name of the program,the operation which failed(preferably in terms which will be meaningful to the user),the name of the file for which the operation failed,and,if some input file(script or source file)is being read,the name andcurrentline number of that file.</p><p>See also question <a href="faqcat1d60.html?sec=stdio#printferrno">12.24</a>.</p><p>References:ISO Sec. 7.1.4, Sec. 7.9.10.4, Sec. 7.11.6.2<br>CT&amp;P Sec. 5.4 p. 73<br>PCS Sec. 11 p. 168, Sec. 14 p. 254<hr><hr><hr><a name="binaryfiles"><h1>comp.lang.c FAQ list<font color=blue>&middot;</font><a href="../../misc/binaryfiles.html"><!-- qtag -->Question 20.5</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How can I write data files which can be read on other machineswith differentword size,byte order,or floating pointformats?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>Themost portablesolution is to usetext files(usually ASCII),written with <TT>fprintf</TT> and read with <TT>fscanf</TT> or the like.(Similar advice also applies to network protocols.)Be skeptical of arguments which imply that textfiles are too big,or that reading and writing them is too slow.Not only is their efficiency frequently acceptable in practice,but the advantagesof being able tointerchange them easily between machines,andmanipulate them with standardtools,can be overwhelming.</p><p>If you must use a binary format,

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -