I am trying to read Data from a Text file & storing it inside a structure having one char pointer & an int variable.
During fetching data from file I know that there will be one string to fetch & one integer value.
I also know the position form where I have to start fetching.
What I don’t know is size of the string.
So, how can I allocate memory for that String.
Sample code is here :
struct filevalue
{
char *string;
int integer;
} value;
fseek(ptr,18,SEEK_SET);//seeking from start of file to position from where I get String
fscanf(ptr,"%s",value.string);//ptr is file pointer
fseek(ptr,21,SEEK_CUR);//Now seeking from current position
fscanf(ptr,"%d",value.integer);
Thanks in advance for your help.
Either
\0into your malloc’d block there so it behaves correctly as a nul-terminated string (and/or save the length too in case you need it)Or
\0etc. as aboveYou said in a comment that the max. string length is bounded, so the first approach is probably fine. You haven’t said how you figure out where the string ends, but I’m assuming there is some delimiter, or it’s right-filled with spaces, or something.