Why does it return an int? There seems to be no reason for this function to not have a void return type. Also, you're opening the file twice, once in line 2 and then again in line 3. I removed the ("primary.txt") from line 2 and it works fine now. I can't exactly tell you why, but I guess opening the file twice like that does something that makes the program not write to it properly.