What is the approach to correctly encoding and parsing variable length messages over TCP? Ex suppose we want to send a message which consists of a mix of string texts and a binary file.
It depends on the protocol you're implementing on top of TCP. Its specification will tell you the correct approach to use.
If you're designing the protocol, generally you just follow the design of whatever existing protocol is closest to what you're doing. Common schemes include:

You encode each message as text ending with a newline character. The receiver just reads blocks of data and searches them for newline characters.

You encode each message as a variable length block and send a 4-byte integer length (in network byte order) prior to each block. The receiver reads blocks of data, when it has 4 bytes, it determines the length of the message, when it has that many more bytes, it "snips off" the message and parses any leftover.

You encode a message in a format like XML or JSON.
TCP transfer of messages of variable length