Torrent files are bencoded files that store the file information downloaded by Bt and the information of the trackers server.
To parse a torrent file, you must first understand the general structure of the torrent file.
Example of a torrent file
| Root (dict)
| -- | Announce (STR)
| -- | Announce-List (list)
| -- | 0 (list)
| -- | 0 (STR)
| -- | 1 (STR)
| -- | Created by (STR)
| -- | Creation date (INT)
| -- | Info (dict)
| -- | Length (INT)
| -- | Name (STR)
| -- | Name. UTF-8 (STR)
| -- | Piece length (INT)
| -- | Pieces (STR)
Then we know the bencoded encoding format:
D -- e Indicates a dict
L -- e Indicates a list
Number: -- represents a string
I -- e indicates an int.
To read and parse data, you must first write the following four methods:
Readdict
Readstring
Readlist
Readint
While loop in readdict Method
While (peekchar ()! = 'E ')
{
Key = readstring
Value = readvalue
Root. Add (Key, value)
}
As for readvalue, it is actually like this:
Tval readvalue ()
{
Tval retval = NULL;
Switch (peekchar ())
{
Case 'D': retval. type = "dict", retval. value = readdict (), break;
Case 'l': retval. type = "list", retval. value = readlist (), break;
Case 'I': retval. type = "int", retval. value = readint (), break;
Defaule: retval. type = "str", retval. value = readstring (), break;
}
Return retval;
}
In short, this is basically the case.