Prepositions often have overlapping usages, but that's not quite the same as "interchangeable". In your examples, notice how you had to switch the form of the word buy to make both sentences sound okay.
Both for and to can be used to explain a reason or motivation for something. However, when used in this way, to is followed by a verb, but for is followed by a noun. Consider:
She goes to the spa on Friday to relax.
She goes to the span on Friday for relaxation.
Here's another interesting example:
The library is a good place for study.
The library is a good place to study.
In this case, the sentences are the identical except for the preposition. However, does this mean the two words are interchangeable? No, it doesn't! These two sentences are both acceptable only because study can function as a noun or as a verb. So, in the first sentence, study functions as a noun, aligning with meanings 8a at Collins:
the act or process of studying
In the second sentence, the two-word phrase to study functions as an infinitive, and therefore study is used as a verb, meaning:
to apply the mind to the learning or understanding of (a subject), esp by reading
I agree with some of the comments about your two sentences; that is, I think "to buy some cake" sounds better than "for buying some cake." But I can see why you'd be confused by this, because we can find some very similar sentences in published books, like:
See if the hotel has a specified area for walking your dog.
Nurses have evaluated a variety of products and methods for bathing older adults.
The whole procedure for getting a license is rather complicated and requires a lot of time.
We could change those sentences to read: to walk your dog, to bathe older adults, and to get a license; any differences in meaning would be minimal. However, sometimes such changes will sound natural and acceptable, and sometimes they won't.
Most importantly, remember that little words like for, in, of, at, with, on, and to are extremely flexible. They typically have several meanings and are used in various ways, including phrasal verbs and prepositional phrases. It will be difficult, if not impossible, to pick two of these words, and give you foolproof guidance that will help you know "which one is correct and wrong." When it comes to these little words, there are simply too many variations to explain everything succinctly.