File Writing

I’ve been trying to write data from a REAL array to a text file and/or a CSV file. I tried doing this directly by attaching the array to the FILE_WRITE function block and using a REAL_TO_BUF function block. Both way writes strange characters in the desired file. One time it wrote “^@^@^@^@”. Another time it wrote a part of the number, however, at the time I was casting the REAL to a string using TO_STRING. That returned “1.234^@^@^@” but it should be “1.234E+01” or something equivilent since the number gets formatted when converting to a string. Could anyone guide me on how to properly write to a file without the data being fudged too much to be usable? Feel free to email me. Or just post it here so everyone can see.

Also it writes “pEA^@” when trying to write to the file via a REAL_TO_BUF.

Hi Noah, That’s a great question with a very interesting answer that others will certainly find useful. The problem is related to the way that the PLC (and all other IEC 61131 PLCs) store variables of different types, and how this data is handled by the *_TO_BUF functions. REAL numbers are stored as 4-byte values in the following format: By en:User:Fresheneesz, traced by User:Stannered - en:Image:Float example.PNG, CC BY-SA 3.0, Link The REAL_TO_BUF function simply copies the number of bytes you specify in the BUF_CNT parameter, without any transformation, to the Byte Array you provide as the BUFFER parameter. Writing this series of bytes to disk will result in a file that is unreadable by humans who haven’t taken the Red Pill. STRING values are stored as a series of ASCII characters, 1 byte per character. So you’d think this would work - and it almost does (as you found). The snag is that the first 2 words (4 bytes) of each STRING value contain information about (a) the maximum length and (b) the actual length of the string. So if you get the length of a string using the LEN function, and then write the first “LEN” characters to a byte array using REAL_TO_BUF, you’ll lose the last 4 bytes of the number - which in your case is the exponent. You would also have seen four weird characters at the start of each number, which were the Length data for the string. The Solution - convert each element of your REAL array to a STRING, and then use the STRING_TO_BUF function - not REAL_TO_BUF - to write each string into the byte array in turn (probably using a FOR … NEXT loop), before sending the byte array to the FILE_WRITE function. You can see from the documentation for *_TO_BUF that the STRING_TO_BUF function takes account of the extra information stored with each string. Let us know if this solves the problem. - Martin.