The problem here is twofold.
Firstly, on Arduinos that don't have a direct USB connection, (i.e., boards like the Uno, Mega, etc that use a separate chip to manage the USB connection) you have no way of knowing if the USB is open or not. That information simply isn't there. The main chip just receives UART serial data (not USB data) as it arrives and that is that.
Secondly, even on the boards that have a direct USB connection (Leonardo, etc) there is no proper way to know if the port has been opened or not. The CDC/ACM protocol simply doesn't have that kind of information (a bit short sighted of them really). The closest you can do is monitor the DTR and/or RTS signals that are encapsulated in the USB data stream. It is down to the host operating system (and maybe even your own program) to exert those signals properly, so isn't foolproof even then.
To check the status of those lines in your sketch you can examine the boolean operator of the Serial
object:
if (Serial) {
// I am connected
} else {
// I am not connected
}
But as I say that can only work on boards like the Leonard - the other indirect boards think they are always connected, since there is no such thing as a connection in UART terminology, only data.