That will not prevent the buffer overflow, but at least I can print out a message and exit the program.
You can still prevent buffer overflow, but if the size of 'descr' and 'seq' is likely to change it's a lot harder. If they're static arrays that won't change then you can just do this
Code:
int getProtein(FILE *in, char descr[], char seq[])
{
int d, s, length = 0;
if(in == NULL)
return -1;
/* Assuming 1001 is the array size */
d = fscanf(in, "%1000[^\n]%*c", descr); // read until '\n' is found
s = fscanf(in, "%1000[^>]%n%*c", seq, &length); // read until '>' is found
if(d == EOF || s == EOF)
return -1;
return length;
}
But if you think the array sizes might change, which shouldn't happen if you choose the sizes well, then you can pass the size of the arrays as arguments and then use sprintf to set up an fscanf format like above
Code:
int getProtein(FILE *in, char descr[], int dlen, char seq[], int slen)
{
char dbuf[20];
char sbuf[20];
int d, s, length = 0;
if(in == NULL)
return -1;
sprintf(dbuf, "%%%d[^\\n]%%*c", dlen);
sprintf(sbuf, "%%%d[^>]%%n%%*c", slen);
d = fscanf(in, dbuf, descr);
s = fscanf(in, sbuf, seq, &length);
if(d == EOF || s == EOF)
return -1;
return length;
}