verilog讀寫文件_第1頁
verilog讀寫文件_第2頁
verilog讀寫文件_第3頁
verilog讀寫文件_第4頁
verilog讀寫文件_第5頁
已閱讀5頁,還剩19頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、系統(tǒng)函數(shù)fopen用于打開一個文件,并還回一個整數(shù)指針然后,fdisplay就可以使用這個文件指針在文件中寫入信息,寫完后,則可以使用fclose系統(tǒng)關(guān)閉這個文件例如:integer write_out_file;定義一個文件指針integer write_out_file=$fopen("write_out_file.txt");$fdisplay(write_out_file,"%hnh",addr,data);fclose("write_out_file");以上語法是將addr,data分別顯示在”%hnh”中的個h的位置,并

2、寫入write_out_file文件指針?biāo)赶虻膚rite_out_file.txt中從文件中讀取數(shù)據(jù),可以用 $readmemb $readmemh 從文件中讀入數(shù)據(jù),該文件格式是一定的reg:data:;$readmemh("file_nametxt",data );就是將file_nametxt中的數(shù)據(jù)讀入到data數(shù)組中,然后就可以使用這些數(shù)據(jù)了還有一種方式可以把指定的數(shù)據(jù)放入指定的存儲器地址單元內(nèi),就是在存放數(shù)據(jù)的文本文件內(nèi),給相應(yīng)的數(shù)據(jù)規(guī)定其內(nèi)存地址,形式如下:address_in_hexadecimal data2f20 兩個系統(tǒng)任務(wù)可以在仿真的任何

3、時刻被執(zhí)行使用,其使用格式共有以下六種: 1) $readmemb("<數(shù)據(jù)文件名>",<存貯器名>);2) $readmemb("<數(shù)據(jù)文件名>",<存貯器名>,<起始地址>);3) $readmemb("<數(shù)據(jù)文件名>",<存貯器名>,<起始地址>,<結(jié)束地址>);4) $readmemh("<數(shù)據(jù)文件名>",<存貯器名>);5) $readmemh("<

4、數(shù)據(jù)文件名>",<存貯器名>,<起始地址>);6) $readmemh("<數(shù)據(jù)文件名>",<存貯器名>,<起始地址>,<結(jié)束地址>); 在這兩個系統(tǒng)任務(wù)中,被讀取的數(shù)據(jù)文件的內(nèi)容只能包含:空白位置(空格,換行,制表格(tab)和form-feeds),注釋行(/形式的和/*.*/形式的都允許),二進(jìn)制或十六進(jìn)制的數(shù)字。數(shù)字中不能包含位寬說明和格式說明,對于$readmemb系統(tǒng)任務(wù),每個數(shù)字必須是二進(jìn)制數(shù)字,對于$readmemh系統(tǒng)任務(wù),每個數(shù)字必須是十六進(jìn)制數(shù)字。數(shù)字中不

5、定值x或X,高阻值z或Z,和下劃線(_)的使用方法及代表的意義與一般Verilog HDL程序中的用法及意義是一樣的。另外數(shù)字必須用空白位置或注釋行來分隔開。 在下面的討論中,地址一詞指對存貯器(memory)建模的數(shù)組的尋址指針。當(dāng)數(shù)據(jù)文件被讀取時,每一個被讀取的數(shù)字都被存放到地址連續(xù)的存貯器單元中去。存貯器單元的存放地址范圍由系統(tǒng)任務(wù)聲明語句中的起始地址和結(jié)束地址來說明,每個數(shù)據(jù)的存放地址在數(shù)據(jù)文件中進(jìn)行說明。當(dāng)?shù)刂烦霈F(xiàn)在數(shù)據(jù)文件中,其格式為字符“”后跟上十六進(jìn)制數(shù)。如: hh.h 對于這個十六進(jìn)制的地址數(shù)中,允許大寫和小寫的數(shù)字。在字符“”和數(shù)字之間不允許存

6、在空白位置??梢栽跀?shù)據(jù)文件里出現(xiàn)多個地址。當(dāng)系統(tǒng)任務(wù)遇到一個地址說明時,系統(tǒng)任務(wù)將該地址后的數(shù)據(jù)存放到存貯器中相應(yīng)的地址單元中去。 對于上面六種系統(tǒng)任務(wù)格式,需補充說明以下五點: 1) 如果系統(tǒng)任務(wù)聲明語句中和數(shù)據(jù)文件里都沒有進(jìn)行地址說明,則缺省的存放起始地址為該存貯器定義語句中的起始地址。數(shù)據(jù)文件里的數(shù)據(jù)被連續(xù)存放到該存貯器中,直到該存貯器單元存滿為止或數(shù)據(jù)文件里的數(shù)據(jù)存完。2) 如果系統(tǒng)任務(wù)中說明了存放的起始地址,沒有說明存放的結(jié)束地址,則數(shù)據(jù)從起始地址開始存放,存放到該存貯器定義語句中的結(jié)束地址為止。3) 如果在系統(tǒng)任務(wù)聲明語句中,起始地址和結(jié)束地址都進(jìn)行了說明,則數(shù)

7、據(jù)文件里的數(shù)據(jù)按該起始地址開始存放到存貯器單元中,直到該結(jié)束地址,而不考慮該存貯器的定義語句中的起始地址和結(jié)束地址。4) 如果地址信息在系統(tǒng)任務(wù)和數(shù)據(jù)文件里都進(jìn)行了說明,那么數(shù)據(jù)文件里的地址必須在系統(tǒng)任務(wù)中地址參數(shù)聲明的范圍之內(nèi)。否則將提示錯誤信息,并且裝載數(shù)據(jù)到存貯器中的操作被中斷。5) 如果數(shù)據(jù)文件里的數(shù)據(jù)個數(shù)和系統(tǒng)任務(wù)中起始地址及結(jié)束地址暗示的數(shù)據(jù)個數(shù)不同的話,也要提示錯誤信息。 下面舉例說明:先定義一個有256個地址的字節(jié)存貯器 mem: reg7:0 mem1:256; 下面給出的系統(tǒng)任務(wù)以各自不同的方式裝載數(shù)據(jù)到存貯器mem中。 initia

8、l $readmemh("mem.data",mem);initial $readmemh("mem.data",mem,16);initial $readmemh("mem.data",mem,128,1); 第一條語句在仿真時刻為0時,將裝載數(shù)據(jù)到以地址是1的存貯器單元為起始存放單元的存貯器中去。第二條語句將裝載數(shù)據(jù)到以單元地址是16的存貯器單元為起始存放單元的存貯器中去,一直到地址是256的單元為止。第三條語句將從地址是128的單元開始裝載數(shù)據(jù),一直到地址為1的單元。在第三種情況中,當(dāng)裝載完畢,系統(tǒng)要檢查在數(shù)據(jù)文件里是

9、否有128個數(shù)據(jù),如果沒有,系統(tǒng)將提示錯誤信息。   ”引用參考”1.打開文件integer file_id;file_id = fopen("file_path/file_name");2.寫入文件/$fmonitor只要有變化就一直記錄$fmonitor(file_id, "%format_char", parameter);eg:$fmonitor(file_id, "%m: %t in1=%d o1=%h", $time, in1, o1);/$fwrite需要觸發(fā)條件才記錄$fwrite(fil

10、e_id, "%format_char", parameter);/$fdisplay需要觸發(fā)條件才記錄$fdisplay(file_id, "%format_char", parameter);$fstrobe();3.讀取文件integer file_id;file_id = $fread("file_path/file_name", "r");4.關(guān)閉文件$fclose(fjile_id);5.由文件設(shè)定存儲器初值$readmemh("file_name", memory_name&quo

11、t;); /初始化數(shù)據(jù)為十六進(jìn)制$readmemb("file_name", memory_name"); /初始化數(shù)據(jù)為二進(jìn)制 轉(zhuǎn):提供了豐富的系統(tǒng)函數(shù),這為Testbench的編寫提供了方便。尤其是IEEE1364-2005,其系統(tǒng)級建模的能力更強(qiáng)。以前我一般常用到的系統(tǒng)函數(shù)只有幾個:$readmemb,$readmemh,$display,$fmonitor,$fwrite,$fopen,$fclose等。通常需要對文件作預(yù)處理,才能用于Testbench讀取。今天又嘗試了幾個其他的文件輸入輸出函數(shù),不需要對文件進(jìn)行預(yù)處理,直接使用需要的文件,只對

12、需要的部分進(jìn)行讀取。$fseek,文件定位,可以從任意點對文件進(jìn)行操作;$fscanf,對文件一行進(jìn)行讀寫。下面是一些常見的應(yīng)用:1、讀寫文件timescale 1 ns/1 nsmodule FileIO_tb;integer fp_r, fp_w, cnt;reg 7:0 reg1, reg2, reg3;initial beginfp_r = $fopen("data_in.txt", "r");fp_w = $fopen("data_out.txt", "w");while(!$feof(fp_r) beg

13、incnt = $fscanf(fp_r, "%d %d %d", reg1, reg2, reg3);$display("%d %d %d", reg1, reg2, reg3);$fwrite(fp_w, "%d %d %dn", reg3, reg2, reg1);end$fclose(fp_r);$fclose(fp_w);endendmodule2、integer file, char;reg eof;initial beginfile = $fopenr("myfile.txt");eof = 0;wh

14、ile (eof = 0) beginchar = $fgetc(file);eof = $feof (file);$display ("%s", char); endend3、文件處理定位define SEEK_SET 0define SEEK_CUR 1define SEEK_END 2integer file, offset, position, r;r = $fseek(file, 0, SEEK_SET); /* Beginning */r = $fseek(file, 0, SEEK_CUR); /* No effect */r = $fseek(fi

15、le, 0, SEEK_END); /* End of file */r = $fseek(file, position, SEEK_SET); /* Previous loc */4、integer r, file, start, count;reg 15:0 mem0:10, r16;r = $fread(file, mem0, start, count);r = $fread(file, r16);5、integer file, position;position = $ftell(file);6、integer file, r, a, b;reg 80*8:1 string;file

16、= $fopenw("output.log");r = $sformat(string, "Formatted %d %x", a, b);r = $sprintf(string, "Formatted %d %x", a, b);r = $fprintf(file, "Formatted %d %x", a, b);7、integer file, r;file = $fopenw("output.log");r = $fflush(file);8、/ This is a pattern fil

17、e - read_pattern.pat / time bin dec hex10: 001 1 120.0: 010 20 02050.02: 111 5 FFF62.345: 100 4 DEADBEEF75.789: XXX 2 ZzZzZzZztimescale 1ns / 10 psdefine EOF 32'hFFFF_FFFFdefine NULL 0define MAX_LINE_LENGTH 1000module read_pattern;integer file, c, r;reg 3:0 bin;reg 31:0 dec, hex;real real_t

18、ime;reg 8*MAX_LINE_LENGTH:0 line; /* Line of text read from file */initialbegin : file_block$timeformat(-9, 3, "ns", 6);$display("time bin decimal hex");file = $fopenr("read_pattern.pat");if (file = NULL) / If error opening filedisable file_block; / Just quitc = $fgetc(

19、file);while (c != EOF)begin/* Check the first character for comment */if (c = "/")r = $fgets(line, MAX_LINE_LENGTH, file);elsebegin/ Push the character back to the file then read the next timer = $ungetc(c, file);r = $fscanf(file," %f:n", real_time);/ Wait until the absolute time

20、 in the file, then read stimulusif ($realtime > real_time)$display("Error - absolute time in file is out of order - %t",real_time);else#(real_time - $realtime)r = $fscanf(file," %b %d %hn",bin,dec,hex);end / if c elsec = $fgetc(file);end / while not EOFr = $fcloser(file);end /

21、 initial/ Display changes to the signalsalways (bin or dec or hex)$display("%t %b %d %h", $realtime, bin, dec, hex);endmodule / read_pattern9、自動比較輸出結(jié)果define EOF 32'hFFFF_FFFFdefine NULL 0define MAX_LINE_LENGTH 1000module compare;integer file, r;reg a, b, expect, clock;wire out;reg MAX_

22、LINE_LENGTH*8:1;parameter cycle = 20;initialbegin : file_block$display("Time Stim Expect Output");clock = 0;file = $fopenr("compare.pat");if (file = NULL)disable file_block;r = $fgets(line, MAX_LINE_LENGTH, file); / Skip commentsr = $fgets(line, MAX_LINE_LENGTH, file);while (!$fe

23、of(file)begin/ Wait until rising clock, read stimulus(posedge clock)r = $fscanf(file, " %b %b %bn", a, b, expect);/ Wait just before the end of cycle to do compare#(cycle - 1)$display("%d %b %b %b %b", $stime, a, b, expect, out);$strobe_compare(expect, out);end / while not EOFr =

24、 $fcloser(file);$stop;end / initialalways #(cycle / 2) clock = !clock; / Clock generatorand #4 (out, a, b); / Circuit under testendmodule / compare10、從文件中讀數(shù)據(jù)到mem(這個好像一般人用的最多了)define EOF 32'HFFFF_FFFF define MEM_SIZE 200_000 module load_mem; integer file, i; reg 7:0 mem0:MEM_S

25、IZE; reg 80*8:1 file_name; initial begin file_name = "data.bin" file = $fopenr(file_name); i = $fread(file, mem0); $display("Loaded %0d entries n", i); i = $fcloser(file); $stop; end endmodule / load_memIntroductionThis describes

26、how you can read and write files in a Verilog model usinga set of user functions, based on the C stdio package. With these functionsyou can perform file input and output directly in Verilog models withouthaving to learn C or the PLI. This code works with VCS, MTI, Verilog-XL

27、,and NC-Verilog (see $fread for one restriction).Note that Synopsys' VCS 6.1, NC-Verilog 3.3, and MTI's ModelSim 5.5offer native support for the IEEE-1364 2001 standard. Verilog-XL does notsupport these tasks except through this PLI application.OverviewThis application no

28、te describes how your Verilog model or testbench canread text and binary files to load memories, apply stimulus, and controlsimulation. Files can also be written. The format of the file I/O functionsis based on the C stdio routines, such as fopen, fgetc, fprintf, and fscanf.The Verilo

29、g language has a rich set of system functions to write files($fdisplay, $fwrite, etc.) but only reads files with a single, fixed format($readmem). In the past if you wanted to read a file that was not in $readmemformat, you would have to learn the Programming Language Interface (PLI)and the C l

30、anguage, write C code to read the file and pass values intoVerilog, then debug the combined C and Verilog code. In addition, the Verilogis limited to 32 open files at a time.However, using the new file I/O system functions you can perform yourfile I/O directly from Verilog. You c

31、an write Verilog HDL to:· read stimulus files to apply patterns to the inputs of a model· read a file of expected values for comparison with your model· read a script of commands to drive a simulation· read either ASCII or binary files into Verilog registers a

32、nd memories· have hundreds of log files open simultaneously (though they are writtento one at a time)Code for all the examples in this file is included in the examples directoryfor the file I/O functions.Note that these system tasks behave the same as the equivalent stdio routines.For example,

33、$fscanf will skip over white-space, including blank lines,just like fscanf(). You can prototype code in C then convert it to Verilog.Differences between fileio and IEEE-1364 Verilog-2001(V2K) standardThe following list describes the differences between my file I/O package(fileio) and the I

34、EEE-1364 Verilog-2001 standard (V2K).1) In fileio $fopen has read, write, append variants:     file = $fopenr("filename");     file = $fopenw("filename");     file = $fopena("filename");In V2K, there is a

35、single $fopen for both multi-channel descriptors(MCD) and file descriptors (FD).  Whether an FD or MCD is producedis indicated by the presence of a mode string added to $fopen in V2K:     file = $fopen("filename", "w");   / FD  &#

36、160;  file = $fopen("filename");        / MCDFileio supports the V2K $fopen format under a package compilation switchbut that then blocks any use of MCDs since it hides the builtin $fopen.2) Fileio $fclose has read and write variants that return

37、 a status:     r = $fcloser(file);     r = $fclosew(file);In V2K, there is a single $fclose for both MCDs and FDs.  It doesnot return a status.  Errors can be determined by using $ferror.Fileio supports the V2K $fclose format under a package compilat

38、ion switchbut that then blocks any use of MCDs since it hides the builtin $fclose.3) Fileio $getchar is not directly supported in Verilog-2001. The operation can be done by using $fgetc('h8000_0000) which makes useof the reserved FD for stdin.4) Fileio defines $fgets as:  

39、60;  r = $fgets(string, n, file);V2K does not support a maximum count "n" of characters to read. Inputin V2K always terminates at end of line and then string assignment to thetarget is done.Fileio's $gets is not directly supported in Verilog 2001.  Theoperation can

40、be done by using:    $fgets(string, 'h8000_0000);that makes use of the reserved FD for stdin.5) Fileio $scanf is not directly supported in Verilog 2001.  Theoperation can be done by using:    $fscanf('h8000_0000, format, args);which makes use of t

41、he reserved FD for stdin.6) Fileio does not support ? as an alias for X; V2K does.7) Fileio does not support reading X or Z for %d format specification;V2K does.8) Fileio supports %f, but not the synonyms %e and %g.  V2K supportsall three.  Fileio does not support %f on in $sscanf; V2K sup

42、portsall specifiers in $sscanf.9) Fileio does not support %u, %z, %v, %t, or %m input format specifiers;V2K supports all of them.10) Fileio supports special character input handling for (i.e. ,oNNN); V2K does not support this (not in LRM).11) Fileio requires that $fread on a memory use "me

43、m0" as the memoryreferend.  V2K requires "mem" since "mem0" will be taken as a registerread.12) Fileio defines $sprintf and $fprintf which are not defined in V2K. V2K defines the $swrite family of tasks for string ouput and allows bothMCDs and FDs in the $fwrite, $

44、fdisplay, $fmonitor, and $fstrobe familiesof tasks.  V2K supports $sformat where the difference in $sformatand $swrite is in the management of format specification strings. Fileio requires a single format string in $sprintf, etc; V2K follows thenormal Verilog convention of treati

45、ng any constant strings as format specifiersfor $swrite.  In V2K, all output format specifications are consistentand produce the same result independent of whether the target is a string,file, or standard output.13) Fileio $ferror only returns a status.  V2k $ferror takes asecond parameter

46、 and stores the error string in that register.  Additionally,V2K $ferror accepts a file descriptor with the value 0 and simple producesthe most recent system error status.14) Fileio requires an argument to $fflush; V2K permits a parameterlesscall and flushes all files (including MCD files) in t

47、hat case.  V2K$fflush supports either MCDs or FDs.15) V2K supports $rewind which Fileio does not.16) Fileio supports $fputc which V2K does not.17) Fileio supports $feof which V2K does not.  Some functionssuch as $fgetc return EOF (-1) but this is not the same.File Input FunctionsThe file I

48、/O system functions and tasks are based on the C stdio routines.For more information on the stdio routines, consult a C manual. The majordifferences between these system tasks and C are caused by the lack ofa pointer variable in the Verilog language. Strings in Verilog are stored

49、in registers, with 8 bits needed to store a single character.OPEN A FILEinteger file;file = $fopenr("filename");file = $fopenw("filename");file = $fopena("filename");The function $fopenr opens an existing file for reading. $fopenw opensa new file for writing, and $fopen

50、a opens a new file for writing whereany data will be appended to the end of the file. The file name can beeither a quoted string or a reg holding the file name. If the file wassuccessfully opened, it returns an integer containing the file number (1.MAX_FILES)or NULL (0) if there was an error. Note t

51、hat these functions are not thesame as the built-in system function $fopen which opens a file for writingby $fdisplay. The files are opened in C with 'rb', 'wb', and 'ab' whichallows reading and writing binary data on the PC. The 'b' is ignored onUnix.CLOSE A FILEinte

52、ger file, r;r = $fcloser(file);r = $fclosew(file);The function $fcloser closes a file for input. $fclosew closes a file foroutput. It returns EOF if there was an error, otherwise 0. Note that theseare not the same as $fclose which closes files for writing.TEST FOR END OF FILEinteger file;reg eof;eof

53、 = $feof(file);The function $feof tests for end of file. If an end-of-file has been reachedwhile reading from the file, a non-zero value is returned; otherwise, a0 is returned.RETURN FILE STATUSinteger file;reg error;error = $ferror(file);The function $ferror returns the error status of a file. If a

54、n errorhas occurred while reading from a file, $ferror returns a non-zero value,else 0. The error value is returned once, then reset to 0.READ A SINGLE CHARACTERinteger file, char;char = $fgetc(file);char = $getc();The function $fgetc reads a single character from the specified file andreturns it. I

55、f the end-of-file is reached, $fgetc returns EOF. You shoulduse a 32-bit register to hold the result from $fgetc to tell the differencebetween the character with the value 255 and EOF. $getc reads from stdin.PUSH BACK A CHARACTERinteger file;reg 7:0 char, r;r = $ungetc(char, file);The function $unge

56、tc pushes the character back into the file stream. Thatcharacter will be the next read by $fgetc. It returns the character ifit was successfully pushed back or EOF if it fails.Note that since there is no $ungetc for stdin in C, there will not beone in the file I/O package.WRITE A SINGLE CHARACTERint

57、eger stream, r, char;r = $fputc(stream, char);The function $fputc writes a single character to the specifiedfile. It returns EOF if there was an error, 0 otherwise.READ A STRINGinteger file, n, r;reg n*8-1:0 string;r = $fgets(string, n, file);r = $gets(string);The function $fgets reads a string from

58、 the file. Characters are readfrom the file into string until a newline is seen, end-of-file is reached,or n-1 characters have been read. If the end-of-file is encountered, $fgetsreturns a 0 and string is unchanged; otherwise, $fgets returns a 1. $getsreads from stdin.The function $gets is no longer

59、 supported by default in fileio v3.4.If you want to use it, you must compile fileio.c with -DGETS. This isbecause some C compilers will give an error message when compilingfileio.c:fileio.o: In function fileio_gets_call:fileio.o: the gets function is dangerous and should not be usedYou can either ig

60、nore this message, or stop using -DGETS to remove thegets function call from fileio.c. READ FORMATTED TEXTinteger file, count;count = $fscanf(file, format, args);count = $sscanf(string, format, args);count = $scanf(format, args);The function $fscanf parses formatted text from the file accordingto the format and writes the results to args. $sscanf parses formattedtext from a string. $scanf parses formated text from stdin. See a C referencemanual for detailed information on fscanf, plus examples later in thi

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論