简体   繁体   English

如果我使用 fscanf 读取文件,我可以使用它来存储它读取的字符数吗?

[英]If I use fscanf to read a file, can I use it to store the number of characters it reads?

I'm trying to use fscanf to read in a bunch of words (all on separate lines) from a file and I want to find the length of each word.我正在尝试使用fscanf从文件中读取一堆单词(全部在单独的行上),并且我想找到每个单词的长度。 Does fscanf allow me to do that or if not, is there any other way to do so? fscanf是否允许我这样做,或者如果没有,还有其他方法吗? I've been looking for an explanation on "input items successfully matched and assigned", but it's still a bit confusing.我一直在寻找关于“输入项成功匹配和分配”的解释,但这仍然有点令人困惑。

To find the text length of a scanned word (or int , double , ...), precede and follow the specifier with a pair of "%n" .要查找扫描单词(或intdouble 、...)的文本长度,请在说明符前后添加一对"%n" "%n" saves the scan offset and does not contribute to the scanf() return value. "%n"保存扫描偏移并且不影响scanf()返回值。

int n1;
int n2;
char buff[100];
//            v-------- space to consume leading white-space
while (scanf(" %n%99s%n", &n1, buff, &n2) == 1) {
  printf("word <%s> length: %d\n", buff, n2 - n1); 
}

The above works equally well had the item been a double with "%f" , an int with "%d" , ....如果项目是带有"%f"double精度,带有"%d"int ,则上述工作同样有效,...。


For "%s" , the length of the string can be found with strlen() after the scan.对于"%s" ,可以在扫描后使用strlen()找到字符串的长度。

char buff[100];
while (scanf("%99s", buff) == 1) {
  printf("word <%s> length: %zu\n", buff, strlen(buff)); 
}

Advanced先进的

Pedantically, input may include embedded null characters .学究式地,输入可能包括嵌入的 null 字符 Null characters are not typically found in text files unless by accident (reading a UTF-16 as UTF-8) or by nefarious users. Null 字符通常不会在文本文件中找到,除非是偶然(将 UTF-16 读取为 UTF-8)或恶意用户。 With "%s" , reading a null character is treated like any other non-white-space.使用"%s" ,读取null 字符将被视为任何其他非空白字符。 Thus the " %n%99s%n" approach can result in a length more than strlen() .因此, " %n%99s%n"方法可能导致长度超过strlen()


I've been looking for an explanation on "input items successfully matched and assigned", but it's still a bit confusing.我一直在寻找关于“输入项成功匹配和分配”的解释,但这仍然有点令人困惑。

The return value of scanf() is roughly the count of matched specifiers - not the length of a word . scanf()的返回值大致是匹配说明符的计数,而不是单词的长度。 The return value may be less than the number of specifiers if scanning was incomplete or EOF if end-of-file first encountered.如果扫描不完整,则返回值可能小于说明符的数量;如果第一次遇到文件结尾,则返回值可能小于EOF "%n" does not contribute to this count. "%n"不计入此计数。 Specifiers with a "*" do not contribute either.带有"*"的说明符也没有贡献。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM