the ticket from budapeste to zagreb i can buy directly on the station? in advanced?
Yep, not a problem to buy it even 5 minutes before departure, anyway all the trains there don't require seat reservation, thus they basically can't be sold out. In case you really want to purchase it in advance online you actually can - via official Hungarian railways website, but, imho, in your case it's too much unnecessary hassle.
and to go to istambul from zagreb (by the route zagreb-belgrade-sofia-istambul) can i buy all the tickets in zagreb? and how long is the trip till istambul?
Better not to buy Belgrade-Istanbul ticket in Zagreb since you'll pay more comparing to the fare when buying in Belgrade. So just go to Serbia and buy it there
Regarding timing: Budapest-Zagreb takes around 6 hours, Zagreb-Belgrade also around 6 hours, while Belgrade-Istanbul, as of now, - whole day and night...speeds are rather low there.
i'll be going in january, is it better buy the tickes in advanced? thank you again!
For the segments Budapest-Zagreb and Zagreb-Belgrade no need to reserve or buy anything in advance. For the Belgrade-Istanbul it might make sense, but only during busy season, while in the off-peak season Istanbul carriage usually not extremely popular. But in case you worry, you can always contact usually reliable Wasteels agency in Belgrade and ask them about sleeper reservation in advance.