Archive: Read / Output Entire File


Read / Output Entire File
 


Section

FileOpen$0 "$TEMP\test.txt" "r"
>FileRead $0 $1
loop:
StrCmp $1 "$\r" loop
StrCmp$1 "$\n" loop
FileClose$0
MessageBox MB_OK "Contents of that file : $1"
>SectionEnd
>
is what I have -- but it's only outputting up to where there's a new line

is there a way to make it read the entire file regardless of returns/newlines?

any help would be great, thanks

Try it like this:

Name "FileReadTest"
OutFile "FileReadTest.exe"

ShowInstDetails show

Section
ClearErrors
FileOpen $0 "$INSTDIR\Foobar.dat" r ; open file
IfErrors done

StrCpy $3 0 ; initialize counter

Loop:
ClearErrors
FileReadByte $0 $1 ; read next byte
IfErrors eof ; end of file ?
IntFmt $2 "0x%02X" $1
IntFmt $4 "0x%08X" $3
DetailPrint "$4 -> $2" ; print: <Address> -> <Byte>
IntOp $3 $3 + 1 ; increase counter
Goto Loop

eof:
FileClose $0 ; close file

done:
SectionEnd


This code will read the entire file byte-by-byte.

parasoul,
Your original function would never work. It's always going to just read one line. The loop is bad too because if you ever just got a single carriage return or a single line feed, you'd be caught in an endless loop. (What's the purpose?)

Assuming that the file is text and not binary, the code below should also work. However, keep in mind that the file can only be 1024 characters (or 8192 if you use the NSIS long strings version.)


!include LogicLib.nsh
...

Section
ClearErrors
FileOpen $0 "$TEMP\text.txt" r
${Do}
FileRead $0 $1
${If} ${Errors}
${ExitDo}
${EndIf}
StrCpy $2 "$2$1"
${Loop}
FileClose $0
; contents should now be in $2:
MessageBox MB_OK "Contents: $\r$2"
SectionEnd