简体   繁体   中英

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. Does fscanf allow me to do that or if not, is there any other way to do so? 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" . "%n" saves the scan offset and does not contribute to the scanf() return value.

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" , ....


For "%s" , the length of the string can be found with strlen() after the scan.

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 characters are not typically found in text files unless by accident (reading a UTF-16 as UTF-8) or by nefarious users. With "%s" , reading a null character is treated like any other non-white-space. Thus the " %n%99s%n" approach can result in a length more than 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 . The return value may be less than the number of specifiers if scanning was incomplete or EOF if end-of-file first encountered. "%n" does not contribute to this count. Specifiers with a "*" do not contribute either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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