I am reading a string from a file in C. The string is supposed to have a specific length and start with thisisnumbr. If both requirements are met, then something else is supposed to happen. Furthermore, I want to prevent that anything unexpected in the file might cause a crash.
My code:
#define MYSTRING "thisisnumb-"
void read_mystring()
{
int c, i = 0, len =0 ;
char input[sizeof( MYSTRING)+2] ;
char check[] = MYSTRING ;
FILE *file ;
file = fopen("/pathto/myfile", "r") ;
if (file) {
while ((c = getc(file)) != EOF)
{
input[i] = c ;
i++ ;
if (i > sizeof(input))
{
len = 1 ;
break ;
}
}
fclose(file) ;
}
if(strncmp(input,check,sizeof(check)-1) == 0 && len == 0)
{
//do something
}
}
So input has the size of MYSTRING plus 2 more characters (supposed to be 2 digits.
In the while loop I am reading myfile and storing it in input. With
if (i > sizeof(input))
{
len = 1 ;
break ;
}
I make sure that the string reading stops if the string in the file appears to be longer than expected.
Then I compare the beginning of the string with strncmp and check if len==0 to make sure the string starts with MYSTRING AND also has the correct length.
If so, something else happens.
This works, meaning that I don't get an Segmentation fault if there is no file, the string in file is too long, or the string in the file doesn't start with MYSTRING.
I was wondering, if there is anything else that might break my program?
And also, when I do printf("input=%s\n",input) at the end of my function, I get my string but also an additional line with garbage?
Any ideas?
fgetsto read each line and then usestrncmpto compare your prefix with the contents of the line... Use a sufficient buffer size to accommodate even long lines or continue to read and discard chars until'\n'is reached.char input[sizeof( MYSTRING)+2] ;-->char input[sizeof( MYSTRING)+2] = "";2)i > sizeof(input)-->i >= sizeof(input)-1