liuchuanwu的个人博客分享 http://blog.sciencenet.cn/u/liuchuanwu

博文

C语言的输入输出函数

已有 4660 次阅读 2015-2-3 09:43 |个人分类:C语言|系统分类:科研笔记| input, output

This part is from the book The C Programming Language. These are popular functions in stdio.h

1. Formatted ouput

int fprintf(FILE *stream, const char *format, ...)

fprintf converts and writes outputs to stream under the control of format. The return value is the number of characters written, or negative if an error occurred.

The format string contains two type of objects: odrdinary characters, which are copied to the output stream, and convension specificatons. each of which causes conversion and printing of the next successive argument of printf. Each conversion specification begins with the character % and ends with a conversion character. Between the % and the conversion character there may be, inorder:

a) flags:

   -, which spcifies left adjustment of converted argument in its field.

   +, which specfies that the number will always be printed with a sign.

   space, if the first character is not a sign, a space will be prefixed.

   0, for numeric conversions, specifies padding to the field width with leading zeros.

   #, which specifies an alternate output form. For o, the first digit will become zero. For x or X, 0x or 0X will be prefixed to a non-zero result. For e, E, f, g and G, the output will always have a decimal point; for gand G, trailling zeros will not be removed.

b) A number specifying a minimum field width. The converted argument will be printed in a field at least this wide, and wider if necessary. If the converted argument has fewer characters than the field width it will be padded on the left (or right, if left adjustment has been requested) to make up the field width. The padding character is normally space, but is 0 if the zero padding flag is present.

c) A period, which separates the field width from the precision.

d) A number, the precision, that specifies the maximum number of characters to be printed from a string, or number of digits to be printed after the decimal point for f, e or E conversions, or the number of significant digits for g or G conversion, or the number of digits to be printed for an integer (leading 0s will be added to make up the necessary width).

e) A length modifier h, l or L. "h" indicates that the corresponding argument is to be printed as a short or unsigned short; "l" indicates that the argument is a long or unsigned long, "L" indicates that the argument is a long double.

Width or precision or both may be specified as *, in which case the value is computed by converting the next argument(s), which must be int.

int printf(const char *format, ...)

printf(...) is equivalent to fprintf(stdout, ...).

int sprintf(char *s, const char *format, ...)

sprintf(...) is the same as printf except that the output is written into the string s, testrminated with ''. s must be big enough to hold the result. the return cont does not include ''.


2. Formatted input

int fscanf(FILE *stream const char *format, ...)

fscanf reads from stream under control of format, and assigns converted values through subsequent arguments, each of which must be a pointer.

The format string usually contains conversion specifications, which are used to direct interpretation of input. The format string may contain:

a) Blanks or tabs, which are not ignored.

b) Ordinary characters (not %), which are expected to match the next non-white space character of the input stream.

c) Conversion specifications, consisting of a %, and optional assignment suppression character *, an optional number of specifying a maximum field width, an optional h, l or L indicting the width of te target, and a conversion character.

A conversion specification determines the conversion of the next input field. Normally the result is placed in the variable pointerd to by the corresponding argument. If assignment suppression is indicated by *, as in %*s, however, the input field is simply skipped (这不同与fprintf格式中的*, 后者表示一个整数,数值由对应的参数计算); no assignment is made. An input field is defined as a string of non-white space characters; it extends either to the next white space character or until the field width, if specified, is exhausted. This implies that scanf will read across line boundaries to find its input, since newlines are white space (White space characters are blank, tab, newline, carriage, return, vertical tab, and formfeed).

The conversion character indicates the interpretation of the input field. The corresponding argument must be a pointer.

Notice the n, [...] and [^...]:

a)n, writes into the argument the number of characters read so far by this call; int *. No input is read. The converted item count is not incremented.

b) [...], matches the longest non-empty string of input characters from the set between brackets; char *; A '' is added.

c) [^...], matches the longest non-empty string of input characters not from the set between brackets; char *; A '' is added. (因此%*[^n]就是跳过至少一个除换行之外的字符)

int scanf(const char *format)

scanf(...) is identical to fscanf(stdin, ...)

int sscanf(const char *s, const char *format, ...)

sscanf(s, ...) is equivalent to scanf(...) except that the inpurt characters are taken fromt he string s.


3. Character input and output functions

int fgetc(FILE *stream)

fgetc returns the next character of stream as an unsigned char (converted to an int), or EOF if end of file or error occurs.

char *fgets(char *s, int n, FILE *stream)

fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered. the newline is included in the array, whch is terminated by ''. fgets returns s or NULL if end of file or error occurs.

int getc(FILE *stream)

getc is equivalent to fgetc except that if it is a macro, it may evaluate stream more than once.

int getchar(void)

getchar is equivalentto getc(stdin).

char *gets(char *s)

gets reads the next input line into the array s; it replaces the terminating newline with ''. It returns s, or NULL if end of file or error occurs.

int putc(int , FILE *stream)

puts is equivalent to fputc except that if it is a macro, it may evaluate stream more than once.

int putchar(int c)

putchar is euquialent to putc(c, stdout)

int puts(const char *s)

puts writes the string s and a newline to stdout. it returns EOF if an error occurs, non-negative otherwise.


[1]In canonical or standard mode of Linux. Linux passes both character and the subsequent Enter to the program. Enter is Line Feed (LF) rather than carriage return (CR) in Linux. This Enter may be read by the subsquent getchar() function. we can use the following codes instead of simple getchar() function

while((character = getchar()) == 'n');


以下转载自http://blog.163.com/ghost_wzf/blog/static/89592171200931010646535/

==========

scanf fscanf,均从第一个非空格的可显示字符开始读起!

标准输入输出函数scanf具有相对较多的转换说明符,它常常作为入门级函数出现在各种教材中。但奇怪的是,[]和n这两种都为c89/c99所规定的标准说明符却鲜少在大多数教材中出现。虽然[]和n说明符的使用频率不及其它说明符,但两者在程序设计中的作用仍然不可小视,尤其是[]说明符。

众所周之,scanf以空白字符为定界符,但如果输入的字符串是以其它字符为定界符的,那怎么办?[]就是专门处理这个问题的转换说明符。[]转换说明符可以通过两种方式产生结果字符集,如果第一个[字符右边没有抑扬符(^),那么处于[]之间的字符就是结果字符集,不在其中的可输入字符都作为定界符;如果左边[符号紧靠一个抑扬符(^),那么意义相反,^和]之间的字符是定界符,其余可输入字符是结果字符集。

在使用[]说明符之前,得先明白两个概念:一是扫描列表。扫描列表(scanlist)指的是包含在[和]两个字符之间除紧靠左边[字符的抑扬符之外的字符,例如:

scanf("%[abcd]", ptr);

abcd组成扫描列表。二是扫描字符集(scanset)。扫描字符集指的是结果字符集,例如上面的例子,结果字符集就是abcd。如果输入一个字符串“cbadkjf”,那么ptr得到的字符串是cbad,kjf三个字符都属于定界符,输入到k字符时输入字符串被截断,kjf三个字符被留在stdin里面。如果带有抑扬符,例如:

scanf("%[^abcd]", ptr);

扫描列表仍然是abcd,但扫描字符集是除abcd外的可输入字符。如果输入字符串“jksferakjjdf”,ptr得到的字符串是“jksfer”。如果想限制输入字符串的字符数量,可以象s说明符那样,在[]前面使用位域,例如:

scanf("%10[^abcd]", ptr);

这样结果字符串最多只能包含10个字符(除''字符外)。

[符号可以作为扫描列表中的一个成员,但]字符除紧贴最左边的[字符或抑扬符两种情况外,其余情况下都不会被看作扫描列表的成员。例如“%[]abcd]”或者“%[^]abcd]”,上述两种情况下]字符属于扫描列表的成员,但如果是“%[ab]cd]”,中间的]字符不会被看作扫描列表的成员,而且输入输出的结果会是乱七八糟的。

对于减号-,只有在紧贴[字符或抑扬字符以及作为扫描列表最后一个成员时,-字符才会被视为扫描列表的成员。c标准把其余情况规定为编译器相关的。大多数编译器把这种情况的减号定义为连字符,例如:

scanf("%[a-zA-Z]", ptr);

那么扫描列表由大小写各26个字母组成。少数编译器仍旧把这种情况下的减号视为扫描列表成员。
fscanf(fd,"%*[^n]n");//%*是虚读,没有存,只是让指针跳过了这个变量!

%n说明符输出有效字符数量,%n在scanf和printf中都可使用。与%n相对应的形参是一个int类型的指针,%n不影响scanf和printf的返回值。例如:

scanf("%d %d%n", &i, &j, &k);

如果输入434 6434,则k等于8,而scanf的返回值仍然为2。又如:

scanf("%c%n", &ch, &k);

输入“sbcdefdg”后,k等于1,而不是8,因为%c只取一个字符,%n输出的是有效字符数量。

%n用在printf函数里,表示输出的字符数量,例如:

printf("i=%d, j=%dn%n", i, j, &k);

在i=343、j=123的情况下,k=12,同时%n不影响printf的返回值,其返回值仍然为12,而不是14。

==============================================================

这个用法是在H264 jm82参考代码上看到的,用来从解码器参数配置文件中读取配置参数,代码如下:

// read the decoder configuration file
if((fd=fopen(config_filename,"r")) == NULL)
{
 snprintf(errortext, ET_SIZE, "Error: Control file %s not foundn",config_filename);
 error(errortext, 300);
}

fscanf(fd,"%s",inp->infile);                // H.26L compressed input bitsream
fscanf(fd,"%*[^n]");

fscanf(fd,"%s",inp->outfile);               // YUV 4:2:2 input format
fscanf(fd,"%*[^n]");

fscanf(fd,"%s",inp->reffile);               // reference file
fscanf(fd,"%*[^n]");

对应的配置文件内容如下:

test.264                 ........H.26L coded bitstream
test_dec.yuv             ........Output file, YUV 4:2:0 format
test_rec.yuv             ........Ref sequence (for SNR)

通过这种方式

inp->infile = "test.264"

inp->outfile = "test_dec.yuv"

inp->reffile = "test_rec.yuv"

而相应的配置文件中的一些注释则不会被读入,这是相当简便的用法,比起通过严格约定注释符并进行一个字符一个字符来解析,这种方式简单了许多!值得借鉴!




Reference:

Brian W. Kernighan & Dennis M. Ritchie. The C Programming Language (Second Edition)



https://wap.sciencenet.cn/blog-1005104-865088.html

上一篇:C Pointers and Arrays Notes
下一篇:打架斗殴要有品
收藏 IP: 155.143.49.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-16 13:17

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部