dup和dup2函数作用

#include <unistd.h>
int dup( int filedes );
int dup2( int filedes, int filedes2 ); //新文件描述符复制filedes,并且将filedes2值作为新文件描述符的值

//dup函数的作用:复制一个现有的句柄,产生一个与“源句柄特性”完全一样的新句柄
// (也即生成一个新的句柄号,并关联到同一个设备,而且它返回的一定是当前可用的
// 文件描述符中的最小数值)


//dup2函数的作用:复制一个现有的句柄到另一个句柄上,目标句柄的特性与“源句柄特性”
// 完全一样(也即首先关闭目标句柄,与设备断连,接着从源句柄完全拷贝复制到目标句柄)

// 这些函数返回的新文件描述符与参数filedes2共享同一个文件表项。 //dup和dup2都是系统服务,window平台对应DuplicateHandle函数/* DUP.C: This program uses the variable old to save * the original stdout. It then opens a new file named * new and forces stdout to refer to it. Finally, it * restores stdout to its original state. */#include <io.h>#include <stdlib.h>#include <stdio.h>void main( void ){ int old; FILE *new; old = _dup( 1 ); /* "old" now refers to "stdout" */ /* Note: file handle 1 == "stdout" */ if( old == -1 ) { perror( "_dup( 1 ) failure" ); exit( 1 ); } write( old, "This goes to stdout first\r\n", 27 ); if( ( new = fopen( "data", "w" ) ) == NULL ) { puts( "Can't open file 'data'\n" ); exit( 1 ); } /* stdout now refers to file "data" */ if( -1 == _dup2( _fileno( new ), 1 ) ) { perror( "Can't _dup2 stdout" ); exit( 1 ); } puts( "This goes to file 'data'\r\n" ); /* Flush stdout stream buffer so it goes to correct file */ fflush( stdout ); fclose( new ); /* Restore original stdout */ _dup2( old, 1 ); puts( "This goes to stdout\n" ); puts( "The file 'data' contains:" ); system( "type data" );}
Output
This goes to stdout first
This goes to file 'data'
This goes to stdout
The file 'data' contains:
This goes to file 'data'

http://hi.baidu.com/qiaoyongfeng/item/88b62e6f557ab309a0cf0f53

C语言中sprintf()函数的用法
sprintf函数的用法
1、该函数包含在stdio.h的头文件中。
2、sprintf和平时我们常用的printf函数的功能很相似。sprintf函数打印到字符串中,而printf函数打印输出到屏幕上。sprintf函数在我们完成其他数据类型转换成字符串类型的操作中应用广泛。
3、sprintf函数的格式:
int sprintf( char *buffer, const char *format [, argument,...] );
除了前两个参数固定外,可选参数可以是任意个。buffer是字符数组名;format是格式化字符串(像:"%3d%6.2f%#x%o",%与#合用时,自动在十六进制数前面加上0x)。只要在printf中可以使用的格式化字符串,在sprintf都可以使用。其中的格式化字符串是此函数的精华。
4、char str[20];
   double f=14.309948;
sprintf(str,"%6.2f",f);
可以控制精度
5、char str[20];
   int a=20984,b=48090;
sprintf(str,"%3d%6d",a,b);
str[]="20984 48090"
可以将多个数值数据连接起来。
6、char str[20];
char s1={'A','B','C'};
char s2={'T','Y','x'};
sprintf(str,"%.3s%.3s",s1,s2);
可以将多个字符串连接成字符串
%m.n在字符串的输出中,m表示宽度,字符串共占的列数;n表示实际的字符数。%m.n在浮点数中,m也表示宽度;n表示小数的位数。
7、可以动态指定,需要截取的字符数
char s1={'A','B','C'};
char s2={'T','Y','x'};
sprintf(str,"%.*s%.*s",2,s1,3,s2);
sprintf(s, "%*.*f", 10, 2, 3.1415926);
8、sprintf(s, "%p", &i);
可以打印出i的地址
上面的语句相当于
sprintf(s, "%0*x", 2 * sizeof(void *), &i);
9、sprintf的返回值是字符数组中字符的个数,即字符串的长度,不用在调用strlen(s)求字符串的长度。
http://hi.baidu.com/actonyuan/item/d23b74106838df6b70d5e855

Related Articles

0 评论 :

发表评论

Quote Of The Day