Sahih Bukhari, Book #77, Hadith #593
Narrated ‘Abdullah: Allah’s Apostle, the truthful and truly-inspired, said,
“Each one of you collected in the womb of his mother for forty days, and then turns into a clot for an equal period (of forty days) and turns into a piece of flesh for a similar period (of forty days) and then Allah sends an angel and orders him to write four things, i.e., his provision, his age, and whether he will be of the wretched or the blessed (in the Hereafter).
Then the soul is breathed into him. And by Allah, a person among you (or a man) may do deeds of the people of the Fire till there is only a cubit or an arm-breadth distance between him and the Fire, but then that writing (which Allah has ordered the angel to write) precedes, and he does the deeds of the people of Paradise and enters it; and a man may do the deeds of the people of Paradise till there is only a cubit or two between him and Paradise, and then that writing precedes and he does the deeds of the people of the Fire and enters it.”