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 wil
i assume you open the file in binary mode since you use fseek.
you could read from the file using fgetc()
since you don't know the size just allocate a buffer with some initial size like 100, then read char by char placing them into the buffer. monitor if the buffer is large enough to hold the characters and if not realloc()
the buffer to a larger size.
If you know the position of the first structure, and the position of the second structure, you also know the total length of the first structure (position of second - position of first). You also know the size of the integer part of the structure, and therefore you can easily calculate the length of the string.
off_t pos1; /* Position of first structure */
off_t pos2; /* Position of second structure */
size_t struct_len = pos2 - pos1;
size_t string_len = struct_len - sizeof(int);
Either
\0
into 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
\0
etc. 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.
Did you mean to SEEK_CUR in your second fseek()? if so, then you know the length of the string. Used a fixed sized buffer.