注:仿真工具为ISE自带simulation
1.读入.txt中的文件
待读入文件为photo.txt,位于所建工程文件夹中。
代码:
integer cnt,i;reg [7:0] mem[31:0];reg [5:0] address;integer fp;initialbegin fp = $fopen("photo.txt","rb"); address = 0; while(!$feof(fp)) begin for(i=0; i<16; i=i+1) begin cnt = $fscanf (fp, "%d",mem[address]); address=address+1; end end $fclose(fp);end注释:
使用句柄fp定位文件之后操作即可;
代码中i < 16的值原则上可以为任意值,一般小于文件中数据总数就好了,因为有 while(!$feof(fp)) 在控制;
以二进制方式读入的;
待读入数据:
结果图:
另外一种写法
reg [7:0] mem[31:0];initialbegin $readmemh("photo.txt",mem);end注:$readmemh和$readmemb分别用来读入源文件为16进制和2进制的文件
结果图:
2.写出.txt文件
代码:
integer fp_write;reg [5:0] write_address;initialbegin fp_write = $fopen("output.txt"); write_address = 0; while(write_address != 32) begin $fwrite(fp_write, "%d ", mem[write_address]); write_address = write_address + 1; if(write_address%8 == 0) $fwrite(fp_write, "\n"); end $fclose(fp_write);end注:
if(write_address%8 == 0) $fwrite(fp_write, "\n"); 为了给文件中加入换行
结果:
整体代码:
`timescale 1 ns / 1 psmodule testbench;reg clk, rst, start;initial begin clk = 0; forever #5 clk = ~clk;endinitial begin rst = 0; #8 rst = 1;endinitial begin start = 0; #502 start = 1;endinteger cnt,i;reg [7:0] mem[31:0];reg [5:0] address;integer fp;initialbegin fp = $fopen("photo.txt","rb"); address = 0; while(!$feof(fp)) begin for(i=0; i<16; i=i+1) begin cnt = $fscanf (fp, "%d",mem[address]); address=address+1; end end $fclose(fp);endinteger fp_write;reg [5:0] write_address;initialbegin fp_write = $fopen("output.txt"); write_address = 0; while(write_address != 32) begin $fwrite(fp_write, "%d ", mem[write_address]); write_address = write_address + 1; if(write_address%8 == 0) $fwrite(fp_write, "\n"); end $fclose(fp_write);endendmodule