Reputation: 11
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.
Upvotes: 1
Views: 518
Reputation: 153457
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
}
Upvotes: 1