简体   繁体   中英

C - How to read with sscanf <int><string><int>?

I have a file with <int><string><int> and I save it into a buffer and read it afterwards using a pipe. The string is alphanumeric.

FILE *est = fopen ("file.txt","r");
fgets( buffer1, 256, est);
write(fd[i][1], buffer1, BUFFERSIZE);

.
.
.

int r = read(fd[i][0], buffer1, BUFFERSIZE);
sscanf(buffer1,"<%d><%s><%d>", &a, b, &c);

The problem is when I read the string it "eats" the ><%d> and it interprets everything as a string. For example if I had <10><5jj8j><10> the variables would be a=10 , b= "5jj8j"><10> and c to whatever it is initialized.

How can I use sscanf to read the string between <> right?

Thanks for the answers.

Since "%s" saves all non-white-space characters and OP does not want '>' to be saved as part of the string, use "%[]" .

Use "%n" to detect if scan completed as n , being at the end, will only change if all the format matched.

// sscanf(buffer1,"<%d><%s><%d>", &a, b, &c);
int n = 0;
char b[100];
sscanf(buffer1,"<%d><%99[^>]><%d>%n", &a, b, &c, &n);
if (n > 0) {
  ; // Scan completed - success;
} else {
  ; // Scan failed
}

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