Reputation: 289
So the current function is supposed to see anything stored between two pound signs (#abc# should give back abc), but if I want to error check to see if there's a pound sign missing, or there's nothing between the pound signs, or that the length of the string in between the two pound signs is greater than a certain number of characters, do I use the fscanf function to do that?
Here's what the fscanf code looks like:
if (fscanf(fp, " %c%[^#]%c", &start, buffer, &end) == 3) {
return strdup(buffer);
} else {
return NULL;
}
Upvotes: 0
Views: 969
Reputation: 753615
If you need to deal with the zero-characters case, then probably fscanf()
is not the right tool. There's a reasonable argument that fscanf()
is seldom the correct tool; you'd do better with fgets()
and sscanf()
.
In this case, I'd collect lines until there's one that's not blank (since that's what the fscanf()
does), and then search for the #
symbols with strchr()
:
char line[4096];
while (fgets(line, sizeof(line), fp) != 0)
{
if (strspn(line, " \t\n") == strlen(line))
continue;
char *hash1 = strchr(line, '#');
if (hash1 == 0)
...error no hashes...
else
{
char *hash2 = strchr(hash1+1, '#');
if (hash2 == 0)
...second hash is missing...
if (hash2 - hash1 > MAX_PERMITTED_STRING_LEN)
...too long a string...
*hash2 = '\0';
char *res = strdup(hash1);
}
}
Upvotes: 1
Reputation:
do I use the fscanf function to do that?
No, you don't. Using the scanf()
family of functions is very rarely a good idea.
char buf[0x1000];
// expect leading `#'
int ch = fgetc(fp);
if (ch != '#') {
puts("Error, missing # at beginning of input");
exit(-1);
}
// read until terminating `#' or until the buffer is exhausted
char *p = buf;
while ((ch = fgetc(fp)) != '#' && p - buf < sizeof(buf)) {
*p++ = ch;
}
// expect terminating `#'
if (ch != '#') {
puts("Error, missing # at end of input");
exit(-1);
}
Upvotes: 1