Output to a Text file

I am trying to write a module that writes the values of all the signals into a text file. A value should be written at every positive edge of the clock. Now File cannot be opened without an initial statement and always block is not allowed in initial statement. How should I write the values into the text file.

module mycomponent(
    input clk,
    input sel,
    input addr,
    input read_write
);
integer fd;
fd= $fopen("Sample.txt", "w");
@always(posedge clk)
   begin
   $fwrite(fd, addr);
   end
$fclose(fd);
endmodule

I wrote this code but this shows an error since file handling can be done using initial statement. What should I do to output all the transactions into the text file?

In reply to nimesh13:

You can add an initial block to open your file and a subsequent forever loop to wait for the clock edge in order to sample your signals. Something like this:


initial begin
  integer fd;
  fd= $fopen("Sample.txt", "w");

  forever begin
    @(posedge clk);
    $fwrite(fd, addr);
  end
end

Please note that an initial block is not synthesizable.

In reply to rodrigoportella:

Yes, it worked.