Patents are a form of protecting intellectual property for inventions and concepts, they must be filed and there cannot be this concept or invention be already existing. When talking about source code, this is not covered by patent law, but by copyright. Your piece of code, your own creation, is owned by you, the same way like books or work of arts are owned by their creators.
To put it simply, patents are about abstract concepts, ideas and mechanisms and need to be applied for, also have only a very limited lifetime, while copyright applies to a concrete work of art (under which code falls) and is automatically given to the creator. Most importantly, you cannot loose copyright, your work is your work (while a patent is only valid if you invent something new, that did not exist prior).
This of course makes proving copyright much easier, if someone uses your interlectual property in a way you did not give permission (of is not fair use), this is a copyright violation. For example I usually publish my code under BSD (if it's a library) or (A)GPL (for programs), both of which have a clause that any copy of the code must retain the license it was licensed under. If someone would take my code and publish it under another license, this is a violation of the terms and conditions, I as the owner of the copyright allow the usage of my work.
With patents it is much harder to prove, because they are about abstract concepts. While for copyright it suffices to show that it is the same work (e.g. by having the same code verbatim), showing that something uses the same abstract idea or mechanism is much harder and requires a deep analysis of the product.
Thats why you see so often patent lawsuits, but not anyone trying to rip of harry potter and sell it as their own