Data loggin HC-SR04 onto HW-125 SD Card Reader Code Problems

I am trying to log data from the HC-SR04 ultrasonic sensor onto the HW-125 SD card reader. I have been experiencing difficulty in getting the code to achieve data logging. At the present the serial monitor output from this code shows a value for distance as calculated through the program but the file created on the SD card is empty with 0kb. Any help with this is most valued.

The code is as follows:

#include <SPI.h>
#include <SD.h>
File myFile;
long duration;
int distance;

void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Initializing_card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables

pinMode(9, OUTPUT); // Sets the trigPin as an Output
pinMode(10, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
digitalWrite(9, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(9, HIGH);
delayMicroseconds(10);
digitalWrite(9, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(10, HIGH);

// Calculating the distance
distance= duration*0.034/2;

// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// if the file opened okay, write to it:
if (myFile) {
myFile.print("Distance :)");
myFile.print(distance);
myFile.println(" cm");
for (int i = 0; i < 200; i++) {
myFile.println(i);
Serial.println(i);

}
}}

if (!SD.begin(10))
...
const int echoPin = 10;

You're using pin 10 as the SD card's SS and also for the ultrasonic's echo.

Even if you weren't using pin 10 for the SD card SS, pin 10 (if you have an Uno anyway, you didn't say) needs to be an output for SPI. (edit: or more correctly, what it mustn't be is a low input, and a reliable way to ensure that is to make it an output.)