National Instruments 320682C User Manual

LabWindows®/CVI
Standard Libraries
Reference Manual
July 1996 Edition
© Copyright 1994, 1996 National Instruments Corporation.
All rights reserved.
Internet Support
gpib.support@natinst.com
GPIB:
daq.support@natinst.com
DAQ:
vxi.support@natinst.com
VXI: LabVIEW: LabWindows: HiQ: VISA: Lookout: FTP Site: Web Address:
BBS United States: (512) 794-5422 or (800) 327-3077 BBS United Kingdom: 01635 551422 BBS France: 1 48 65 15 59
(512) 418-1111
lv.support@natinst.com
lw.support@natinst.com
hiq.support@natinst.com
visa.support@natinst.com
lookout.support@natinst.com
ftp.natinst.com
www.natinst.com
Bulletin Board Support
FaxBack Support
Telephone Support (U.S.)
Tel: (512) 795-8248 Fax: (512) 794-5678
International Offices
Australia 03 9 879 9422, Austria 0662 45 79 90 0, Belgium 02 757 00 20, Canada (Ontario) 519 622 9310, Canada (Québec) 514 694 8521, Denmark 45 76 26 00, Finland 90 527 2321, France 1 48 14 24 24, Germany 089 741 31 30, Hong Kong 2645 3186, Italy 02 413091, Japan 03 5472 2970, Korea 02 596 7456, Mexico 95 800 010 0793, Netherlands 0348 433466, Norway 32 84 84 00, Singapore 2265886, Spain 91 640 0085, Sweden 08 730 49 70, Switzerland 056 200 51 51, Taiwan 02 377 1200, U.K. 01635 523545
National Instruments Corporate Headquarters
6504 Bridge Point Parkway Austin, TX 78730-5039 Tel: (512) 794-0100

Warranty

The media on which you receive National Instruments software are warranted not to fail to execute programming instructions, due to defects in materials and workmanship, for a period of 90 days from date of shipment, as evidenced by receipts or other documentation. National Instruments will, at its option, repair or replace software media that do not execute programming instructions if National Instruments receives notice of such defects during the warranty period. National Instruments does not warrant that the operation of the software shall be uninterrupted or error free.
A Return Material Authorization (RMA) number must be obtained from the factory and clearly marked on the outside of the package before any equipment will be accepted for warranty work. National Instruments will pay the shipping costs of returning to the owner parts which are covered by warranty.
National Instruments believes that the information in this manual is accurate. The document has been carefully reviewed for technical accuracy. In the event that technical or typographical errors exist, National Instruments reserves the right to make changes to subsequent editions of this document without prior notice to holders of this edition. The reader should consult National Instruments if errors are suspected. In no event shall National Instruments be liable for any damages arising out of or related to this document or the information contained in it.
E
XCEPT AS SPECIFIED HEREIN
SPECIFICALLY DISCLAIMS ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
C
USTOMER’S RIGHT TO RECOVER DAMAGES CAUSED BY FAULT OR NEGLIGENCE ON THE PART OF NATIONAL
I
NSTRUMENTS SHALL BE LIMITED TO THE AMOUNT THERETOFORE PAID BY THE CUSTOMER WILL NOT BE LIABLE FOR DAMAGES RESULTING FROM LOSS OF DATA CONSEQUENTIAL DAMAGES
, N
ATIONAL INSTRUMENTS MAKES NO WARRANTIES, EXPRESS OR IMPLIED, AND
. N
ATIONAL INSTRUMENTS
,
PROFITS, USE OF PRODUCTS, OR INCIDENTAL OR
,
EVEN IF ADVISED OF THE POSSIBILITY THEREOF
. This limitation of the liability of
.
National Instruments will apply regardless of the form of action, whether in contract or tort, including negligence. Any action against National Instruments must be brought within one year after the cause of action accrues. National Instruments shall not be liable for any delay in performance due to causes beyond its reasonable control. The warranty provided herein does not cover damages, defects, malfunctions, or service failures caused by owner’s failure to follow the National Instruments installation, operation, or maintenance instructions; owner’s modification of the product; owner’s abuse, misuse, or negligent acts; and power failure or surges, fire, flood, accident, actions of third parties, or other events outside reasonable control.

Copyright

Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent of National Instruments Corporation.

Trademarks

NI-DAQ®, NI-488.2™, and NI-488.2M™ are trademarks of National Instruments Corporation.
Product and company names listed are trademarks or trade names of their respective companies.
WARNING REGARDING MEDICAL AND CLINICAL USE
OF NATIONAL INSTRUMENTS PRODUCTS
National Instruments products are not designed with components and testing intended to ensure a level of reliability suitable for use in treatment and diagnosis of humans. Applications of National Instruments products involving medical or clinical treatment can create a potential for accidental injury caused by product failure, or by errors on the part of the user or application designer. Any use or application of National Instruments products for or involving medical or clinical treatment must be performed by properly trained and qualified medical personnel, and all traditional medical safeguards, equipment, and procedures that are appropriate in the particular situation to prevent serious injury or death should always continue to be used when National Instruments products are being used. National Instruments products are NOT intended to be a substitute for any form of established process, procedure, or equipment used to monitor or safeguard human health and safety in medical or clinical treatment.

Contents

_____________________________________________________________________________
About This Manual
Organization of This Manual .......................................................................................xvii
Conventions Used in This Manual...............................................................................xix
The LabWindows/CVI Documentation Set .................................................................xx
Related Documentation................................................................................................xx
Customer Communication ...........................................................................................xx
Chapter 1 ANSI C Library
Low-Level I/O Functions.............................................................................................1-2
Standard Language Additions......................................................................................1-2
Character Processing....................................................................................................1-5
String Processing..........................................................................................................1-5
Input/Output Facilities .................................................................................................1-6
errno Set by File I/O Functions....................................................................................1-6
Mathematical Functions...............................................................................................1-6
Time and Date Functions .............................................................................................1-6
Control Functions.........................................................................................................1-7
ANSI C Library Function Reference............................................................................1-9
fdopen...............................................................................................................1-9
................................................................................................................1-1
...........................................................................................................xvii
Chapter 2 Formatting and I/O Library
Formatting and I/O Library Function Overview..........................................................2-1
The Formatting and I/O Library Function Panels............................................2-1
The String Manipulation Functions .................................................................2-3
The Special Nature of the Formatting and Scanning Functions.......................2-3
Formatting and I/O Library Function Reference..........................................................2-4
ArrayToFile......................................................................................................2-4
CloseFile ..........................................................................................................2-7
CompareBytes..................................................................................................2-7
CompareStrings................................................................................................2-8
CopyBytes........................................................................................................2-9
CopyString .......................................................................................................2-10
FileToArray......................................................................................................2-11
FillBytes...........................................................................................................2-13
FindPattern.......................................................................................................2-13
Fmt ...................................................................................................................2-14
FmtFile.............................................................................................................2-15
FmtOut .............................................................................................................2-16
GetFileInfo.......................................................................................................2-17
........................................................................................2-1
© National Instruments Corporation v LabWindows/CVI Standard Libraries
Contents
GetFmtErrNdx..................................................................................................2-18
GetFmtIOError.................................................................................................2-18
GetFmtIOErrorString.......................................................................................2-19
NumFmtdBytes................................................................................................2-20
OpenFile...........................................................................................................2-20
ReadFile ...........................................................................................................2-22
ReadLine ..........................................................................................................2-23
Scan..................................................................................................................2-24
ScanFile............................................................................................................2-25
ScanIn...............................................................................................................2-25
SetFilePtr..........................................................................................................2-26
StringLength.....................................................................................................2-28
StringLowerCase..............................................................................................2-28
StringUpperCase ..............................................................................................2-29
WriteFile...........................................................................................................2-29
WriteLine .........................................................................................................2-30
Using the Formatting and Scanning Functions............................................................2-31
Introductory Formatting and Scanning Examples............................................2-31
Formatting Functions.......................................................................................2-32
Formatting Functions—Format String.................................................2-33
Formatting Modifiers ...........................................................................2-35
Formatting Integer Modifiers (%i, %d, %x, %o, %c)..............2-35
Formatting Floating-Point Modifiers (%f)...............................2-37
Formatting String Modifiers (%s)............................................2-38
Fmt, FmtFile, FmtOut—Asterisks (*) Instead of Constants
in Format Specifiers.............................................................................2-39
Fmt, FmtFile, FmtOut—Literals in the Format String.........................2-40
Scanning Functions..........................................................................................2-40
Scanning Functions—Format String....................................................2-41
Scanning Modifiers..............................................................................2-43
Scanning Integer Modifiers (%i, %d, %x, %o, %c).................2-43
Scanning Floating-Point Modifiers (%f)..................................2-45
Scanning String Modifiers (%s)...............................................2-46
Scan, ScanFile, ScanIn—Asterisks (*) Instead of Constants
in Format Specifiers.............................................................................2-48
Scan, ScanFile, ScanIn—Literals in the Format String .......................2-48
Formatting and I/O Library Programming Examples..................................................2-49
Fmt/FmtFile/FmtOut Examples in C ...............................................................2-50
Integer to String....................................................................................2-50
Long Integer to String..........................................................................2-51
Real to String in Floating-Point Notation ............................................2-51
Real to String in Scientific Notation....................................................2-52
Integer and Real to String with Literals...............................................2-53
Two Integers to ASCII File with Error Checking................................2-53
Real Array to ASCII File in Columns and with Comma Separators ...2-53
LabWindows/CVI Standard Libraries vi © National Instruments Corporation
Contents
Integer Array to Binary File, Assuming a Fixed
Number of Elements.............................................................................2-54
Real Array to Binary File, Assuming a Fixed
Number of Elements.............................................................................2-54
Real Array to Binary File, Assuming a Variable
Number of Elements.............................................................................2-55
A Variable Portion of a Real Array to a Binary File............................2-55
Concatenating Two Strings..................................................................2-56
Appending to a String ..........................................................................2-56
Creating an Array of File Names .........................................................2-57
Writing a Line Containing an Integer with Literals to
the Standard Output..............................................................................2-58
Writing to the Standard Output without
a Linefeed/Carriage Return..................................................................2-58
Scan/ScanFile/ScanIn Examples in C..............................................................2-59
String to Integer....................................................................................2-59
String to Long Integer..........................................................................2-60
String to Real........................................................................................2-60
String to Integer and Real.....................................................................2-61
String to String.....................................................................................2-62
String to Integer and String..................................................................2-63
String to Real, Skipping over Non-Numeric Characters
in the String..........................................................................................2-63
String to Real, After Finding a Semicolon in the String......................2-64
String to Real, After Finding a Substring in the String........................2-64
String with Comma-Separated ASCII Numbers to Real Array ...........2-65
Scanning Strings That Are Not NUL-Terminated ...............................2-65
Integer Array to Real Array..................................................................2-66
Integer Array to Real Array with Byte Swapping................................2-66
Integer Array Containing 1-Byte Integers to Real Array.....................2-66
String Containing Binary Integers to Integer Array.............................2-67
String Containing an IEEE-Format Real Number
to a Real Variable.................................................................................2-67
ASCII File to Two Integers with Error Checking................................2-68
ASCII File with Comma Separated Numbers to Real Array,
with Number of Elements at Beginning of File ...................................2-68
Binary File to Integer Array, Assuming a Fixed
Number of Elements.............................................................................2-69
Binary File to Real Array, Assuming a Fixed Number of Elements....2-69
Binary File to Real Array, Assuming a Variable
Number of Elements.............................................................................2-69
Reading an Integer from the Standard Input........................................2-70
Reading a String from the Standard Input............................................2-70
Reading a Line from the Standard Input..............................................2-71
© National Instruments Corporation vii LabWindows/CVI Standard Libraries
Contents
Chapter 3 Analysis Library
Analysis Library Function Overview...........................................................................3-1
The Analysis Library Function Panels.............................................................3-1
Reporting Analysis Errors................................................................................3-4
Analysis Library Function Reference...........................................................................3-4
Abs1D...............................................................................................................3-4
Add1D..............................................................................................................3-5
Add2D..............................................................................................................3-5
Clear1D ............................................................................................................3-6
Copy1D ............................................................................................................3-7
CxAdd ..............................................................................................................3-7
CxAdd1D .........................................................................................................3-8
CxDiv...............................................................................................................3-9
CxDiv1D ..........................................................................................................3-10
CxLinEv1D ......................................................................................................3-11
CxMul ..............................................................................................................3-12
CxMul1D..........................................................................................................3-12
CxRecip............................................................................................................3-13
CxSub...............................................................................................................3-14
CxSub1D..........................................................................................................3-15
Determinant......................................................................................................3-16
Div1D...............................................................................................................3-16
Div2D...............................................................................................................3-17
DotProduct .......................................................................................................3-18
GetAnalysisErrorString....................................................................................3-19
Histogram.........................................................................................................3-19
InvMatrix..........................................................................................................3-20
LinEv1D...........................................................................................................3-21
LinEv2D...........................................................................................................3-22
MatrixMul ........................................................................................................3-23
MaxMin1D.......................................................................................................3-24
MaxMin2D.......................................................................................................3-24
Mean.................................................................................................................3-25
Mul1D ..............................................................................................................3-26
Mul2D ..............................................................................................................3-27
Neg1D ..............................................................................................................3-28
Set1D................................................................................................................3-28
Sort...................................................................................................................3-29
StdDev..............................................................................................................3-29
Sub1D...............................................................................................................3-30
Sub2D...............................................................................................................3-31
Subset1D ..........................................................................................................3-32
ToPolar.............................................................................................................3-32
...............................................................................................................3-1
Hints for Using Analysis Function Panels ...........................................3-3
LabWindows/CVI Standard Libraries viii © National Instruments Corporation
ToPolar1D........................................................................................................3-33
ToRect..............................................................................................................3-34
ToRect1D.........................................................................................................3-35
Transpose .........................................................................................................3-36
Error Conditions...........................................................................................................3-37
Chapter 4 GPIB/GPIB-488.2 Library
GPIB Library Function Overview................................................................................4-1
GPIB Functions Library Function Panels ........................................................4-1
GPIB Library Concepts................................................................................................4-5
GPIB Libraries and the GPIB Dynamic Link Library/Device Driver..............4-5
Guidelines and Restrictions for Using the GPIB Libraries..............................4-6
Device and Board Functions............................................................................4-7
Automatic Serial Polling..................................................................................4-7
Autopolling Compatibility...................................................................4-8
Hardware Interrupts and Autopolling...............................................................4-8
Read and Write Termination............................................................................4-9
Timeouts...........................................................................................................4-9
Global Variables for the GPIB Library............................................................4-10
Different Levels of Functionality Depending on Platform and GPIB Board...4-10
Windows 95..........................................................................................4-10
Native 32-Bit Driver.................................................................4-10
Compatibility Driver................................................................4-11
Windows NT........................................................................................4-11
Limitations on Transfer Size............................................................................4-11
Multithreading..................................................................................................4-11
Notification of SRQ and Other GPIB Events...................................................4-12
Synchronous Callbacks........................................................................4-12
Asynchronous Callbacks......................................................................4-12
Driver Version Requirements...............................................................4-12
GPIB Function Reference ............................................................................................4-13
CloseDev..........................................................................................................4-13
CloseInstrDevs.................................................................................................4-14
ibInstallCallback...............................................................................................4-14
SRQI, RQS, and Auto Serial Polling...................................................4-16
CallbackFunction .................................................................................4-17
ibNotify ............................................................................................................4-17
eventMask ............................................................................................4-18
SRQI, RQS, and Auto Serial Polling...................................................4-19
CallbackFunction .................................................................................4-19
Restrictions on Operations in Asynchronous Callbacks......................4-20
OpenDev...........................................................................................................4-21
ThreadIbcnt ......................................................................................................4-22
ThreadIbcntl.....................................................................................................4-22
Contents
...........................................................................................4-1
© National Instruments Corporation ix LabWindows/CVI Standard Libraries
Contents
ThreadIberr.......................................................................................................4-23
ThreadIbsta.......................................................................................................4-25
Chapter 5 RS-232 Library
RS-232 Library Function Overview.............................................................................5-1
The RS-232 Library Function Panels...............................................................5-1
Using RS-485...................................................................................................5-3
Reporting RS-232 Errors..................................................................................5-3
XModem File Transfer Functions....................................................................5-3
Troubleshooting ...............................................................................................5-3
RS-232 Cable Information...............................................................................5-4
Handshaking.....................................................................................................5-6
RS-232 Library Function Reference ............................................................................5-8
CloseCom.........................................................................................................5-8
ComBreak.........................................................................................................5-9
ComFromFile...................................................................................................5-9
ComRd .............................................................................................................5-11
ComRdByte......................................................................................................5-12
ComRdTerm.....................................................................................................5-12
ComSetEscape..................................................................................................5-14
ComToFile .......................................................................................................5-15
ComWrt............................................................................................................5-16
ComWrtByte ....................................................................................................5-17
FlushInQ...........................................................................................................5-18
FlushOutQ........................................................................................................5-19
GetComStat......................................................................................................5-19
GetInQLen........................................................................................................5-20
GetOutQLen.....................................................................................................5-21
GetRS232ErrorString.......................................................................................5-22
InstallComCallback..........................................................................................5-22
OpenCom .........................................................................................................5-25
OpenComConfig ..............................................................................................5-26
ReturnRS232Err...............................................................................................5-28
SetComTime ....................................................................................................5-29
SetCTSMode....................................................................................................5-30
SetXMode.........................................................................................................5-31
XModemConfig ...............................................................................................5-31
XModemReceive..............................................................................................5-33
XModemSend...................................................................................................5-34
Error Conditions...........................................................................................................5-36
.................................................................................................................5-1
Software Handshaking .........................................................................5-6
Hardware Handshaking........................................................................5-7
LabWindows/CVI Standard Libraries x © National Instruments Corporation
Chapter 6 DDE Library
DDE Library Function Overview.................................................................................6-1
The DDE Library Function Panels...................................................................6-1
DDE Clients and Servers..................................................................................6-2
The DDE Callback Function............................................................................6-2
DDE Links........................................................................................................6-4
A DDE Library Example Using Microsoft Excel and LabWindows/CVI.......6-5
DDE Library Function Reference ................................................................................6-6
AdviseDDEDataReady.....................................................................................6-6
BroadcastDDEDataReady................................................................................6-8
ClientDDEExecute...........................................................................................6-10
ClientDDERead................................................................................................6-10
ClientDDEWrite...............................................................................................6-12
ConnectToDDEServer .....................................................................................6-13
DisconnectFromDDEServer.............................................................................6-15
GetDDEErrorString..........................................................................................6-15
RegisterDDEServer..........................................................................................6-16
ServerDDEWrite..............................................................................................6-19
SetUpDDEHotLink..........................................................................................6-20
SetUpDDEWarmLink......................................................................................6-21
TerminateDDELink..........................................................................................6-22
UnregisterDDEServer ......................................................................................6-23
Error Conditions...........................................................................................................6-23
Contents
......................................................................................................................6-1
Chapter 7 TCP Library
TCP Library Function Overview..................................................................................7-1
TCP Library Function Reference.................................................................................7-3
Error Conditions...........................................................................................................7-12
.......................................................................................................................7-1
The TCP Library Function Panels....................................................................7-1
TCP Clients and Servers ..................................................................................7-2
The TCP Callback Function.............................................................................7-2
ClientTCPRead ................................................................................................7-3
ClientTCPWrite................................................................................................7-4
ConnectToTCPServer ......................................................................................7-5
DisconnectFromTCPServer .............................................................................7-7
DisconnectTCPClient.......................................................................................7-7
GetTCPErrorString...........................................................................................7-8
RegisterTCPServer...........................................................................................7-8
ServerTCPRead................................................................................................7-10
ServerTCPWrite...............................................................................................7-11
UnregisterTCPServer.......................................................................................7-11
© National Instruments Corporation xi LabWindows/CVI Standard Libraries
Contents
Chapter 8 Utility Library
The Utility Library Function Panels.............................................................................8-1
Utility Library Function Reference..............................................................................8-5
Beep..................................................................................................................8-5
Breakpoint........................................................................................................8-6
CloseCVIRTE ..................................................................................................8-6
Cls ....................................................................................................................8-7
CopyFile...........................................................................................................8-7
CVILowLevelSupportDriverLoaded................................................................8-8
DateStr..............................................................................................................8-9
Delay ................................................................................................................8-9
DeleteDir..........................................................................................................8-10
DeleteFile.........................................................................................................8-10
DisableBreakOnLibraryErrors .........................................................................8-11
DisableInterrupts..............................................................................................8-12
DisableTaskSwitching......................................................................................8-12
EnableBreakOnLibraryErrors ..........................................................................8-15
EnableInterrupts...............................................................................................8-15
EnableTaskSwitching.......................................................................................8-16
ExecutableHasTerminated................................................................................8-16
GetBreakOnLibraryErrors................................................................................8-17
GetBreakOnProtectionErrors ...........................................................................8-18
GetCVIVersion.................................................................................................8-18
GetCurrentPlatform..........................................................................................8-19
GetDir...............................................................................................................8-20
GetDrive...........................................................................................................8-20
GetExternalModuleAddr..................................................................................8-21
GetFileAttrs......................................................................................................8-23
GetFileDate ......................................................................................................8-24
GetFileSize.......................................................................................................8-25
GetFileTime .....................................................................................................8-26
GetFirstFile ......................................................................................................8-27
GetFullPathFromProject ..................................................................................8-29
GetInterruptState..............................................................................................8-30
GetKey .............................................................................................................8-30
GetModuleDir ..................................................................................................8-31
GetNextFile......................................................................................................8-33
GetPersistentVariable.......................................................................................8-33
GetProjectDir ...................................................................................................8-34
GetStdioPort.....................................................................................................8-35
GetStdioWindowOptions.................................................................................8-35
GetStdioWindowPosition.................................................................................8-36
GetStdioWindowSize.......................................................................................8-37
GetStdioWindowVisibility...............................................................................8-37
...................................................................................................................8-1
LabWindows/CVI Standard Libraries xii © National Instruments Corporation
Contents
GetSystemDate.................................................................................................8-38
GetSystemTime................................................................................................8-39
GetWindowDisplaySetting...............................................................................8-39
InitCVIRTE......................................................................................................8-40
inp.....................................................................................................................8-42
inpw..................................................................................................................8-42
InStandaloneExecutable...................................................................................8-43
KeyHit..............................................................................................................8-43
LaunchExecutable............................................................................................8-44
LaunchExecutableEx........................................................................................8-47
LoadExternalModule........................................................................................8-49
LoadExternalModuleEx...................................................................................8-52
MakeDir ...........................................................................................................8-54
MakePathname.................................................................................................8-55
outp...................................................................................................................8-56
outpw................................................................................................................8-56
ReadFromPhysicalMemory..............................................................................8-57
ReadFromPhysicalMemoryEx.........................................................................8-58
ReleaseExternalModule ...................................................................................8-59
RenameFile.......................................................................................................8-60
RetireExecutableHandle...................................................................................8-61
RoundRealToNearestInteger............................................................................8-61
RunExternalModule.........................................................................................8-62
SetBreakOnLibraryErrors ................................................................................8-63
SetBreakOnProtectionErrors............................................................................8-64
SetDir ...............................................................................................................8-66
SetDrive............................................................................................................8-66
SetFileAttrs ......................................................................................................8-67
SetFileDate.......................................................................................................8-68
SetFileTime......................................................................................................8-70
SetPersistentVariable .......................................................................................8-71
SetStdioPort......................................................................................................8-71
SetStdioWindowOptions..................................................................................8-72
SetStdioWindowPosition .................................................................................8-74
SetStdioWindowSize........................................................................................8-75
SetStdioWindowVisibility ...............................................................................8-76
SetSystemDate .................................................................................................8-76
SetSystemTime ................................................................................................8-77
SplitPath...........................................................................................................8-77
SyncWait..........................................................................................................8-79
SystemHelp ......................................................................................................8-79
TerminateExecutable........................................................................................8-82
Timer................................................................................................................8-83
TimeStr.............................................................................................................8-83
TruncateRealNumber .......................................................................................8-84
© National Instruments Corporation xiii LabWindows/CVI Standard Libraries
Contents
UnloadExternalModule....................................................................................8-84
WriteToPhysicalMemory.................................................................................8-85
WriteToPhysicalMemoryEx.............................................................................8-86
Chapter 9 X Property Library
X Property Library Overview.......................................................................................9-1
The X Property Library Function Panels .........................................................9-1
X Interclient Communication...........................................................................9-2
Property Handles and Types ............................................................................9-3
Communicating with Local Applications ........................................................9-3
The Hidden Window........................................................................................9-3
Property Callback Functions............................................................................9-4
Error Codes ......................................................................................................9-4
Using the Library Outside of LabWindows/CVI.............................................9-7
X Property Library Function Reference.......................................................................9-7
ConnectToXDisplay.........................................................................................9-7
CreateXProperty...............................................................................................9-9
CreateXPropType.............................................................................................9-10
DestroyXProperty.............................................................................................9-12
DestroyXPropType...........................................................................................9-13
DisconnectFromXDisplay................................................................................9-14
GetXPropErrorString .......................................................................................9-15
GetXPropertyName..........................................................................................9-15
GetXPropertyType...........................................................................................9-16
GetXPropTypeName........................................................................................9-17
GetXPropTypeSize...........................................................................................9-18
GetXPropTypeUnit ..........................................................................................9-19
GetXWindowPropertyItem ..............................................................................9-20
GetXWindowPropertyValue............................................................................9-22
InstallXPropertyCallback.................................................................................9-25
PutXWindowPropertyItem...............................................................................9-27
PutXWindowPropertyValue.............................................................................9-29
RemoveXWindowProperty..............................................................................9-31
UninstallXPropertyCallback ............................................................................9-33
.........................................................................................................9-1
Chapter 10 Easy I/O for DAQ Library
Easy I/O for DAQ Library Function Overview............................................................10-1
Advantages of Using the Easy I/O for DAQ Library.......................................10-1
Limitations of Using the Easy I/O for DAQ Library .......................................10-2
Easy I/O for DAQ Library Function Panels.....................................................10-2
Device Numbers...............................................................................................10-4
Channel String for Analog Input Functions.....................................................10-4
Command Strings.............................................................................................10-6
LabWindows/CVI Standard Libraries xiv © National Instruments Corporation
...........................................................................................10-1
Contents
Channel String for Analog Output Functions ..................................................10-7
Valid Counters for the Counter/Timer Functions ............................................10-7
Easy I/O for DAQ Function Reference........................................................................10-8
AIAcquireTriggeredWaveforms ......................................................................10-8
AIAcquireWaveforms......................................................................................10-13
AICheckAcquisition.........................................................................................10-15
AIClearAcquisition ..........................................................................................10-15
AIReadAcquisition...........................................................................................10-16
AISampleChannel ............................................................................................10-17
AISampleChannels...........................................................................................10-18
AIStartAcquisition ...........................................................................................10-19
AOClearWaveforms.........................................................................................10-20
AOGenerateWaveforms...................................................................................10-21
AOUpdateChannel...........................................................................................10-22
AOUpdateChannels..........................................................................................10-23
ContinuousPulseGenConfig.............................................................................10-24
CounterEventOrTimeConfig............................................................................10-26
CounterMeasureFrequency ..............................................................................10-29
CounterRead.....................................................................................................10-32
CounterStart .....................................................................................................10-33
CounterStop......................................................................................................10-34
DelayedPulseGenConfig..................................................................................10-34
FrequencyDividerConfig..................................................................................10-37
GetAILimitsOfChannel....................................................................................10-40
GetChannelIndices...........................................................................................10-41
GetChannelNameFromIndex ...........................................................................10-42
GetDAQErrorString.........................................................................................10-43
GetNumChannels.............................................................................................10-44
GroupByChannel..............................................................................................10-44
ICounterControl ...............................................................................................10-45
PlotLastAIWaveformsPopup ...........................................................................10-47
PulseWidthOrPeriodMeasConfig.....................................................................10-48
ReadFromDigitalLine.......................................................................................10-49
ReadFromDigitalPort.......................................................................................10-51
SetEasyIOMultitaskingMode...........................................................................10-53
WriteToDigitalLine..........................................................................................10-53
WriteToDigitalPort...........................................................................................10-55
Error Conditions...........................................................................................................10-57
Appendix A Customer Communication
Glossary Index
© National Instruments Corporation xv LabWindows/CVI Standard Libraries
................................................................................................................................G-1
......................................................................................................................................I-1
.............................................................................................A-1
Contents
Tables
Table 1-1. ANSI C Standard Library Classes .........................................................................1-1
Table 1-2. C Locale Information Values.................................................................................1-3
Table 2-1. The Formatting and I/O Library Function Tree.....................................................2-2
Table 3-1. The Analysis Library Function Tree......................................................................3-1
Table 3-2. Analysis Library Error Codes................................................................................3-37
Table 4-1. The GPIB Functions Library Function Tree..........................................................4-2
Table 5-1. The RS-232 Library Function Tree........................................................................5-1
Table 5-2. PC Cable Configuration.........................................................................................5-4
Table 5-3. DTE to DCE Cable Configuration.........................................................................5-5
Table 5-4. PC to DTE Cable Configuration............................................................................5-5
Table 5-5. Bit Definitions for the GetComStat Function........................................................5-20
Table 5-6. RS-232 Library Error Codes..................................................................................5-36
Table 6-1. DDE Library Function Tree...................................................................................6-1
Table 6-2. DDE Transaction Types (xType)...........................................................................6-4
Table 6-3. DDE Library Error Codes......................................................................................6-24
Table 7-1. The TCP Library Function Tree ............................................................................7-1
Table 7-2. TCP Transaction Types (xType)............................................................................7-3
Table 7-3. TCP Library Error Codes.......................................................................................7-12
Table 8-1. The Utility Library Function Tree .........................................................................8-1
Table 9-1. The X Property Library Function Tree..................................................................9-2
Table 9-2. Predefined Property Types.....................................................................................9-3
Table 9-3. X Property Library Error Types and Descriptions.................................................9-5
Table 9-4. Status Values for InstallXPropertyCallback..........................................................9-26
Table 10-1. Easy I/O for DAQ Function Tree.........................................................................10-2
Table 10-2. Valid Counters.....................................................................................................10-7
Table 10-3. Definition of Am 9513: Counter +1 ....................................................................10-28
Table 10-4. Adjacent Counters................................................................................................10-30
Table 10-5. Easy I/O for DAQ Error Codes............................................................................10-57
LabWindows/CVI Standard Libraries xvi © National Instruments Corporation

About This Manual

The LabWindows/CVI Standard Libraries Reference Manual contains information about the LabWindows/CVI standard libraries—the Graphics Library, the Analysis Library, the Formatting and I/O Library, the GPIB Library, the GPIB-488.2 Library, the RS-232 Library, the Utility Library, and the system libraries. The LabWindows/CVI Standard Libraries Reference Manual is intended for use by LabWindows/CVI users who have already completed the Getting Started with LabWindows/CVI tutorial and are familiar with the LabWindows/CVI User Manual. To use this manual effectively, you should be familiar with LabWindows/CVI and DOS fundamentals.

Organization of This Manual

The LabWindows/CVI Standard Libraries Reference Manual is organized as follows.
Chapter 1, ANSI C Library, describes the ANSI C Standard Library as implemented in LabWindows/CVI.
Chapter 2, Formatting and I/O Library, describes the functions in the LabWindows/CVI Formatting and I/O Library, and contains many examples of how to use them. The Formatting and I/O Library contains functions that input and output data to files and manipulate the format of data in a program.
Chapter 3, Analysis Library, describes the functions in the LabWindows/CVI Analysis Library. The Analysis Library Function Overview section contains general information about the Analysis Library functions and panels. The Analysis Library Function Reference section contains an alphabetical list of the function descriptions.
Chapter 4, GPIB/GPIB-488.2 Library, describes the NI-488 and NI-488.2 functions in the LabWindows/CVI GPIB Library, as well as the Device Manager functions in LabWindows/CVI. The GPIB Library Function Overview section contains general information about the GPIB Library functions and panels, the GPIB DLL, and guidelines and restrictions you should know when using the GPIB Library. Detailed descriptions of the NI-488 and NI-488.2 functions can be found in your NI-488.2 function reference manual. The GPIB Function Reference section contains an alphabetical list of descriptions for the Device Manager functions, the callback installation functions, and the functions for returning the thread-specific status variables.
© National Instruments Corporation xvii LabWindows/CVI Standard Libraries
About This Manual
Chapter 5, RS-232 Library, describes the functions in the LabWindows/CVI RS-232 Library. The RS-232 Library Function Overview section contains general information about the RS-232 Library functions and panels. The RS-232 Library Function Reference section contains an alphabetical list of function descriptions.
Chapter 6, DDE Library, describes the functions in the LabWindows/CVI DDE (Dynamic Data Exchange) Library. The DDE Library Function Overview section contains general information about the DDE Library functions and panels. The DDE Library Function Reference section contains an alphabetical list of function descriptions. This library is available for LabWindows/CVI for Microsoft Windows only.
Chapter 7, TCP Library, describes the functions in the LabWindows/CVI TCP (Transmission Control Protocol) Library. The TCP Library Function Overview section contains general information about the TCP Library functions and panels. The TCP Library Function Reference section contains an alphabetical list of function descriptions.
Chapter 8, Utility Library, describes the functions in the LabWindows/CVI Utility Library. The Utility Library contains functions that do not fit into any of the other LabWindows/CVI libraries. The Utility Library Function Panels section contains general information about the Utility Library functions and panels. The Utility Library Function Reference section contains an alphabetical list of function descriptions.
Chapter 9, X Property Library, describes the functions in the Lab/Windows CVI X Property Library. The X Property Library contains functions that read and write properties to and from X Windows. The X Property Library Overview section contains general information about the X Property Library functions and panels. The X Property Library Function Reference section contains an alphabetical list of function descriptions.
Chapter 10, Easy I/O for DAQ Library describes the functions in the Easy I/O for DAQ Library. The Easy I/O for DAQ Library Function Overview section contains general information about the functions, and guidelines and restrictions you should know when using the Easy I/O for DAQ Library. The Easy I/O for DAQ Library Function Reference section contains an alphabetical list of function descriptions.
Appendix A, Customer Communication, contains forms you can use to request help from National Instruments or to comment on our products and manuals.
The Glossary contains an alphabetical list and description of terms used in this manual, including abbreviations, acronyms, metric prefixes, mnemonics, and symbols.
The Index contains an alphabetical list of key terms and topics in this manual, including the page where you can find each one.
LabWindows/CVI Standard Libraries xviii © National Instruments Corporation

Conventions Used in This Manual

The following conventions are used in this manual:
About This Manual
bold
italic Italic text denotes emphasis, a cross reference, or an introduction to
bold italic Bold italic text denotes a note, caution, or warning.
monospace Text in this font denotes text or characters that you should literally
italic monospace
< > Angle brackets enclose the name of a key. A hyphen between two
Bold text denotes a parameter, menu item, return value, function panel item, or dialog box button or option.
a key concept.
enter from the keyboard. Sections of code, programming examples, and syntax examples also appear in this font. This font also is used for the proper names of disk drives, paths, directories, programs, subprograms, subroutines, device names, variables, filenames, and extensions, and for statements and comments taken from program code.
Italic text in this font denotes that you must supply the appropriate words or values in the place of these items.
or more key names enclosed in angle brackets denotes that you should simultaneously press the named keys–for example, <Ctrl-Alt-Delete>.
» The » symbol leads you through nested menu items and dialog
box options to a final action. The sequence
File » Page Setup » Options » Substitute Fonts
directs you to pull down the item, select option from the last dialog box.
paths Paths in this manual are denoted using backslashes (\) to
separate drive names, directories, and files, as in
drivename\dir1name\dir2name\myfile
IEEE 488, IEEE 488 and IEEE 488.2 refer to the ANSI/IEEE Standard 488.1-1987, IEEE 488.2 and the ANSI/IEEE Standard 488.2-1992, respectively, which define the GPIB.
Abbreviations, acronyms, metric prefixes, mnemonics, symbols, and terms are listed in the
Glossary.
© National Instruments Corporation xix LabWindows/CVI Standard Libraries
Options
, and finally select the
File
menu, select the
Substitute Fonts
Page Setup
About This Manual

The LabWindows/CVI Documentation Set

For a detailed discussion of the best way to use the LabWindows/CVI documentation set, see the section Using the LabWindows/CVI Documentation Set in Chapter 1, Introduction to LabWindows/CVI of Getting Started with LabWindows/CVI.

Related Documentation

The following documents contain information that you may find helpful as you read this manual:
ANSI/IEEE Standard 488.1-1987, IEEE Standard Digital Interface for Programmable
Instrumentation
ANSI/IEEE Standard 488.2-1992, IEEE Standard Codes, Formats, Protocols, and Common Commands
Harbison, Samuel P. and Guy L. Steele, Jr., C: A Reference Manual, Englewood Cliffs, NJ: Prentice-Hall, Inc., 1995.
Nye, Adrian. Xlib Programming Manual. Sebastopol, California: O'Reilly & Associates,
1994. ISBN 0-937175-27-7
Gettys, James and Robert W. Scheifler. Xlib—C Language X Interface, MIT X Consortium Standard. Cambridge, Massachussetts: X Consortium, 1994. ISBN (none)

Customer Communication

National Instruments wants to receive your comments on our products and manuals. We are interested in the applications you develop with our products, and we want to help if you have problems with them. To make it easy for you to contact us, this manual contains comment and technical support forms for you to complete. These forms are in the appendix, Customer
Communication, at the end of this manual.
LabWindows/CVI Standard Libraries xx © National Instruments Corporation

Chapter 1 ANSI C Library

This chapter describes the ANSI C Standard Library as implemented in LabWindows/CVI.
Note:
When you link your executable or DLL with an external compiler, you are using the
ANSI C library of the external compiler.

Table 1-1. ANSI C Standard Library Classes

Class Header File
Character Handling <ctype.h>
Character Testing Character Case Mapping
Date and Time <time.h>
Time Operations Time Conversion
Time Formatting Localization <locale.h> Mathematics <math.h>
Trigonometric Functions
Hyperbolic Functions
Exp and Log Functions
Power Functions Nonlocal Jumping <setjmp.h> Signal Handling <signal.h> Input/Output <stdio.h>
Open/Close
Read/Write/Flush
Line Input/Output
Character Input/Output
Formatted Input/Output
Buffer Control
File Positioning
File System Operations
Error Handling
(continues)
© National Instruments Corporation 1-1 LabWindows/CVI Standard Libraries
ANSI C Library Chapter 1
Table 1-1. ANSI C Standard Library Classes (Continued)
General Utilities <stdlib.h>
String to Arithmetic Expression
Random Number Generation
Memory Management
Searching and Sorting
Integer Arithmetic
Multibyte Character Sets
Program Termination
Environment String Handling <string.h>
Byte Operations
String Operations
String Searching
Collation Functions
Miscellaneous

Low-Level I/O Functions

Under UNIX you can use the low-level I/O functions (such as open, sopen, read, and write) from the system library by including system header files in your program. Under
Windows you can use these functions by including cvi\include\ansi\lowlvlio.h in your program. No function panels are provided for these functions.

Standard Language Additions

LabWindows/CVI does not support extended character sets that require more than 8 bits per character. As a result, the wide character type wchar_t is identical to the single-byte char type. LabWindows/CVI accepts wide character constants specified with the L prefix (as in
L‘ab’), but only the first character is significant. Furthermore, library functions that use the wchar_t type operate only on 8-bit characters.
LabWindows/CVI supports variable argument functions using the ANSI C macros, with one exception: none of the unspecified arguments can have a struct type. As a result, the macro va_arg (ap, type) should never be used when type is a structure.
Note:
Under UNIX, LabWindows/CVI implements only the C locale as defined by the ANSI C standard. The native locale, which is specified by the empty string, "", is also the C locale. The following table shows the locale information values for the C locale.
LabWindows/CVI Standard Libraries 1-2 © National Instruments Corporation
LabWindows/CVI will not warn you about this error.
Chapter 1 ANSI C Library

Table 1-2. C Locale Information Values

Name Type C locale Value Description
decimal_point char * "."
thousands_sep char * ""
grouping char * "" int_curr_symbol char * ""
currency_symbol char * ""
mon_decimal_point char * "" mon_thousands_sep char * ""
mon_grouping char * "" positive_sign char * ""
negative_sign char * ""
int_frac_digits char CHAR_MAX
frac_digits char CHAR_MAX
p_cs_precedes char CHAR_MAX
p_sep_by_space char CHAR_MAX
n_cs_precedes char CHAR_MAX n_sep_by_space char CHAR_MAX
p_sign_posn char CHAR_MAX
n_sign_posn char CHAR_MAX
Decimal point character for non-monetary values.
Non-monetary digit group separator character or characters.
Non-monetary digit groupings. The three-character international currency
symbol, plus the character used to separate the international symbol from the monetary quantity.
The local currency symbol for the current locale.
Decimal point character for monetary values. Monetary digit group separator character or
characters. Monetary digit groupings. Sign character or characters for non-negative
monetary quantities. Sign character or characters for negative
monetary quantities. Digits appear to the right of the decimal point
for international monetary formats. Digits appear to the right of the decimal point
for other than international monetary formats.
currency_symbol
1 if
precedes non-
negative monetary values; 0 if it follows.
currency_symbol
1 if
is separated from non-negative monetary values by a space; else 0.
p_cs_precedes
Like
p_sep_by_space
Like
, for negative values.
, for negative
values. The positioning of
positive_sign
for a
non-negative monetary quantity, then its
currency_symbol
The positioning of
.
negative_sign
for a
negative monetary quantity, then its
currency_symbol
.
© National Instruments Corporation 1-3 LabWindows/CVI Standard Libraries
ANSI C Library Chapter 1
Under Windows, LabWindows/CVI implements the default locale by using the appropriate items from the Intl section of the WIN.INI file and appropriate Microsoft Windows functions. Anything not mentioned here has the same behavior under the default locale as specified in the C locale.
For the LC_NUMERIC locale:
decimal_point maps to the value of sDecimal.
thousands_sep maps to the value of sThousand. For the LC_MONETARY locale:
currency_symbol maps to the value of sCurrency.
mon_decimal_point maps to the value of sDecimal.
mon_thousands_sep maps to the value of sThousand.
frac_digits maps to the value of iCurrDigits.
int_frac_digits maps to the value of iCurrDigits.
p_cs_precedes and n_cs_precedes are set to 1 if iCurrency equals 0 or 2,
otherwise they are set to 0.
p_sep_by_space and n_sep_by_space are set to 0 if iCurrency equals 0 or 1, otherwise they are set to 0.
p_sign_posn and n_sign_posn are determined by the value of iNegCurr as follows:
Value of
Value of iNegCurr
p_sign_posn/n_sign_posn
0, 4 0 1, 5, 8, 9 1 3, 7, 10 2 63 24
For the LC_CTYPE locale:
isalnum maps to the Windows function isCharAlphaNumeric.
isalpha maps to the Windows function isCharAlpha.
LabWindows/CVI Standard Libraries 1-4 © National Instruments Corporation
Chapter 1 ANSI C Library
islower maps to the Windows function isCharLower.
isupper maps to the Windows function isCharUpper.
tolower maps to the Windows function AnsiLower.
toupper maps to the Windows function AnsiUpper.
For the LC_TIME locale:
strftime uses the following items from the WIN.INI file for the appropriate format
specifiers: sTime, iTime, s1159, s2359, iTLZero, sShortDate, and sLongDate.
The names of the weekdays and the names of the months match the language version of LabWindows/CVI. That is, a German version of LabWindows/CVI would use the German names of months and days.
For the LC_COLLATE locale:
strcoll maps to the Windows function lstrcmp.
Because LabWindows/CVI does not support extended character sets that require more than a byte per character, a multibyte character in LabWindows/CVI is actually a single byte character. Likewise, a multibyte sequence is a sequence of single byte characters. Because a multibyte character is the same as a wide character, the conversion functions described in these sections do little more than return their inputs as outputs.

Character Processing

LabWindows/CVI implements all the ANSI C character processing facilities as both macros and functions. The macros are disabled when the LabWindows/CVI debugging level is set to Standard or Extended, so that user protection is available for the arguments to the functions.

String Processing

Under UNIX, the strcoll function is equivalent to strcmp and its behavior is not affected by the LC_COLLATE locale. Under Windows, strcoll is equivalent to the Windows function lstrcmp. For both platforms, the function strxfrm performs a string copy using strncpy and returns the length of its second argument.
© National Instruments Corporation 1-5 LabWindows/CVI Standard Libraries
ANSI C Library Chapter 1

Input/Output Facilities

The function rename fails if the target file already exists. Under Microsoft Windows, rename fails if the source and target files are on different disk drives. Under UNIX, rename fails if the source and target files are on different file systems.
The functions fgetpos and ftell set errno to EFILPOS on error.

errno Set by File I/O Functions

The errno global variable is set to indicate specific error conditions by the ANSI C file I/O functions and the low-level I/O functions. The possible values of errno are declared in cvi\include\ansi\errno.h. There is a base set of values that is common to all platforms. There are additional values that are specific to particular platforms.
Under Windows 3.1, errno gives very limited information. If the operating system returns an error, errno is set to EIO.
Under Windows 95 and NT, you can call the Windows SDK GetLastError function to obtain system specific information when errno is set to one of the following values:
EACCES EBADF EIO ENOENT ENOSPC

Mathematical Functions

The macro HUGE_VAL defined in the header math.h as well as the macros FLT_EPSILON, FLT_MAX, FLT_MIN, DBL_EPSILON, DBL_MAX, DBL_MIN, LDBL_EPSILON, LDBL_MAX,
and DBL_MIN defined in the header float.h all refer to variables. Consequently, these macros cannot be used in places where constant expressions are required, such as in global initializations.

Time and Date Functions

Function time returns the number of seconds since January 1, 1990. Functions mktime and localtime require time zone information to produce correct results.
LabWindows/CVI obtains time zone information from the environment variable named TZ, if it exists. The value of this variable should have the format AAA[S]HH[:MM]BBB, where optional items are in square brackets.
LabWindows/CVI Standard Libraries 1-6 © National Instruments Corporation
Chapter 1 ANSI C Library
The AAA and BBB fields specify the names of the standard and daylight savings time zones, respectively (such as EST for Eastern Standard Time and EDT for Eastern Daylight Time). The optional sign field S indicates whether the local time zone is to the west (+) or to the east (-) of UTC (Greenwich Mean Time). The hour field (HH) and the optional minutes field (:MM) specify the number of hours and minutes from UTC. As an example, the string EST05EDT specifies the time zone information for the eastern part of the United States.
The functions gmtime, localtime, and mktime make corrections for daylight savings time (DST). LabWindows/CVI uses a set of rules for determining when daylight savings time begins and ends. A string in the messages file cvimsgs.txt in the LabWindows/CVI bin directory specifies these rules. The following is the default value of this string.
":(1986)040102+0:110102-0:(1967)040102-0:110102-0" This states that for the years from 1986 to the present, DST begins at 2:00 a.m. on the first
Sunday in April, and ends at 2:00 a.m. on the last Sunday in October. For the years from 1967 to 1985, DST begins at 2:00 a.m. on the last Sunday in March, and ends at 2:00 a.m. on the last Sunday in October. You can change the way LabWindows/CVI determines DST by changing this string in the cvimsgs.txt file. The countmsg.exe program must be executed after changing the text file. You should execute the following line.
countmsg cvimsgs.txt

Control Functions

The assert macro defined by LabWindows/CVI does not print diagnostics to the standard error stream when the debugging level is anything other than None. Instead, when the value of its argument evaluates to zero, LabWindows/CVI will display a dialog box with a message containing the file name, line number, and expression that caused the assert to fail.
Under UNIX, system passes the specified command to the Bourne shell (sh) as input, as if the current process was performing a wait(2V) system call and was waiting until the shell terminated. Callbacks are not called while the command is executing.
Under Windows, the executable can be either an MS DOS or Microsoft Windows executable, including *.exe, *.com, *.bat, and *.pif files. The function does not return until the command terminates, and user keyboard and mouse events are ignored until the command exits. Callbacks for asynchronous events, such as idle events, Windows messages, and VXI interrupts, PostDeferredCall calls, and DAQ events are called while the command is executing. If you need to execute a command built into command.com such as copy, dir, and others, you can call system with the command command.com /C DosCommand args, where DosCommand is the shell command you would like executed. Refer to your DOS documentation for further help with command.com. DOS executables (.exe, .com, and .bat files) use the settings in _default.pif (in your Windows directory) when they are running. You can change their priority, display options, and more by editing _default.pif
© National Instruments Corporation 1-7 LabWindows/CVI Standard Libraries
ANSI C Library Chapter 1
or by creating another .pif file. Refer to your Microsoft Windows documentation for help on creating and editing .pif files.
If the function is passed a null pointer, LabWindows/CVI returns a non zero value if a command processor is available. Under UNIX, if the argument is not a null pointer, the program returns a zero. Under Microsoft Windows, if the argument is not a null pointer, the program returns zero if the program was successfully started, otherwise it returns one of the following error codes.
-1 System was out of memory, executable file was corrupt, or relocations were invalid.
-3 File was not found.
-4 Path was not found.
-6 Attempt was made to dynamically link to a task, or there was a sharing or network protection error.
-7 Library required separate data segments for each task.
-9 There was insufficient memory to start the application.
-11 Windows version was incorrect.
-12 Executable file was invalid. Either it was not a Windows application or there was an error in the .EXE image.
-13 Application was designed for a different operating system.
-14 Application was designed for MS-DOS 4.0.
-15 Type of executable file was unknown.
-16 Attempt made to load a real-mode application (developed for an earlier Windows version.)
-17 Attempt was made to load a second instance of an executable file containing multiple data segments that were not marked read-only.
-20 Attempt was made to load a compressed executable file. The file must be decompressed before it can be loaded.
-21 Dynamic-link library (DLL) file was invalid. One of the DLLs required to run this application was corrupt.
-22 Application requires Microsoft Windows 32-bit extensions.
-23 Could not find toolhelp.dll or toolhelp.dll is corrupted.
-24 Could not allocate a GetProcUserDefinedHandle.
The exit function does not actually flush and close the open streams. LabWindows/CVI leaves files open so that they may be used from within the Interactive Window after execution of the project terminates. The Close Libraries menu option under the Run menu performs this library cleanup. This library cleanup is also performed when you restart execution of the project by selecting Run Project from the Run menu. The argument passed to function exit is not used by the LabWindows/CVI environment. Under UNIX, standalone executables created by LabWindows/CVI return the value of the argument passed to the exit function.
LabWindows/CVI Standard Libraries 1-8 © National Instruments Corporation
Chapter 1 ANSI C Library
The UNIX version of LabWindows/CVI works with all the signals supported by UNIX in addition to the ANSI C signals.

ANSI C Library Function Reference

For ANSI C function descriptions, consult a reference work such as C: A Reference Manual which is listed in the Related Documentation section of About This Manual. Alternatively, you can use LabWindows/CVI function panel help. The following function description is provided because it is an extension of the ANSI C function set.

fdopen

FILE *fp =
Note:
This function is available only in the Windows version of LabWindows/CVI.
Purpose
You can use this function to obtain a pointer to a buffered I/O stream from a file handle returned by one of the following functions.
open (low-level I/O) sopen (low-level I/O)
You can use the return value just as if you had obtained it from fopen. (Although this function is not in the ANSI standard, it is included in this library because it
returns a pointer to a buffered I/O stream.)
Parameters
Input
fdopen
fileHandle mode
fileHandle
(int
integer File handle returned by open or sopen. string Specifies the read/write, binary/text, and append modes.
, char *
mode
);
Return Value
fp
Return Codes
NULL (0)
© National Instruments Corporation 1-9 LabWindows/CVI Standard Libraries
Failure. More specific information is in errno.
FILE *
Pointer to a buffered I/O file stream.
ANSI C Library Chapter 1
Parameter Discussion mode is the same as the mode parameter to fopen.
You should use a mode value that is consistent with the mode in which you originally opened the file. If you use write capabilities that were not enabled when the file handle was originally opened, the call to fdopen succeeds, but any attempt to write fails. For instance, if you originally opened the file for reading only, you can pass "rw" to fdopen, but any call to fwrite fails.
LabWindows/CVI Standard Libraries 1-10 © National Instruments Corporation

Chapter 2 Formatting and I/O Library

This chapter describes the functions in the LabWindows/CVI Formatting and I/O Library, and contains many examples of how to use them. The Formatting and I/O Library contains functions that input and output data to files and manipulate the format of data in a program.
The Formatting and I/O Library Function Overview section contains general information about the Formatting and I/O Library functions and panels. Because the Formatting and I/O Library differs in many respects from the other LabWindows/CVI libraries, it is very important to read the overview before reading the other sections of this chapter.
The Formatting and I/O Library Function Reference section contains an alphabetical list of function descriptions. This section is helpful for determining the syntax of the file I/O and string manipulation functions.
The Using the Formatting and Scanning Functions section describes in detail this special class of functions. Although these functions are listed in the function reference, their versatility and complex nature require a more complete discussion.
The final section, Formatting and I/O Library Programming Examples, contains many examples of program code that call Formatting and I/O Library functions. Most of the examples use the formatting and scanning functions.

Formatting and I/O Library Function Overview

This section contains general information necessary for understanding the Formatting and I/O Library functions and panels.

The Formatting and I/O Library Function Panels

The Formatting and I/O Library function panels are grouped in a tree structure according to the types of operations performed. The Formatting and I/O Library function tree is shown in Table 2-1.
The first- and second-level bold headings in the tree are the names of function classes and subclasses. Function classes and subclasses are groups of related function panels. The third-level headings in plain text are the names of individual function panels. The names of the functions are in bold italics to the right of the function panels. Refer to the Sample Function Panels for the Formatting and Scanning Functions section later in this chapter for more information.
© National Instruments Corporation 2-1 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2

Table 2-1. The Formatting and I/O Library Function Tree

Formatting and I/O
File I/O
Open File OpenFile Close File CloseFile Read from File ReadFile Write to File WriteFile Array to File ArrayToFile File to Array FileToArray Get File Information GetFileInfo Set File Pointer SetFilePtr
String Manipulation
Get String Length StringLength String to Lowercase StringLowerCase String to Uppercase StringUpperCase Fill Bytes FillBytes Copy Bytes CopyBytes Copy String CopyString Compare Bytes CompareBytes Compare Strings CompareStrings Find Pattern FindPattern Read Line ReadLine Write Line WriteLine
Data Formatting
Formatting Functions
Fmt to Memory (Sample Panel) Fmt Fmt to File (Sample Panel) FmtFile Fmt to Stdout (Sample Panel) FmtOut
Scanning Functions
Scan from Mem (Sample Panel) Scan Scan from File (Sample Panel) ScanFile Scan from Stdin (Sample Panel) ScanIn
Status Functions
Get # Formatted Bytes NumFmtdBytes
Get Format Index Error GetFmtErrNdx Get I/O Error GetFmtIOError Get I/O Error String GetFmtIOErrorString
The classes and subclasses in the tree are described below:
The File I/O function panels open, close, read, write, and obtain information about files.
The String Manipulation function panels manipulate strings and character buffers.
LabWindows/CVI Standard Libraries 2-2 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
The Data Formatting function panels perform intricate formatting operations with a single
function call. – Formatting Functions, a subclass of Data Formatting, contains function panels that
combine and format one or more source items into a single target item.
Scanning Functions, a subclass of Data Formatting, contains function panels that
transform a single source item into several target items.
Status Functions, a subclass of Data formatting, contains function panels that return
information about the success or failure of a formatting or scanning call.
The online help with each panel contains specific information about operating each function panel.

The String Manipulation Functions

The functions in the String Manipulation class perform common operations such as copying one string to another, comparing two strings, or finding the occurrence of a string in a character buffer. These functions are similar in purpose to the standard C string functions.

The Special Nature of the Formatting and Scanning Functions

The formatting and scanning functions are different in nature from the other functions in the LabWindows/CVI libraries. With few exceptions, each LabWindows/CVI library function has a fixed number of parameters, and each parameter has a definite data type. Each formatting and scanning function, however, takes a variable number of parameters, and the parameters can be of various data types. This difference is necessary to give the formatting and scanning functions versatility.
For instance, a single Scan function call performs disparate operations, such as the following.
Find the two numeric values in the string:
"header: 45, -1.03e-2"
and place the first value in an integer variable and the second in a real variable.
Take the elements from an integer array, swap the high and low bytes in each element, and place the resulting values in a real array.
To perform these operations, each formatting and scanning function takes a format string as one of its parameters. In effect, a format string is a mini-program that instructs the formatting and scanning functions on how to transform the input arguments to the output arguments. For conciseness, format strings are constructed using single-character codes. These codes are
© National Instruments Corporation 2-3 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
described in detail in the Using the Formatting and Scanning Functions section later in this chapter.
You may find the formatting and scanning functions more difficult to learn than other LabWindows/CVI functions. To help you in this learning process, read the discussions in the Formatting and I/O Library Programming Examples section at the end of this chapter.

Formatting and I/O Library Function Reference

This section gives a brief description of each of the functions available in the LabWindows/CVI Formatting and I/O Library. The LabWindows/CVI Formatting and I/O Library functions are arranged alphabetically.

ArrayToFile

status
int
Purpose
Saves an array to a file using various formatting options. The function handles creating, opening, writing, and closing the file. The file can later be read back into an array using the FileToArray function.
Parameters
Input
ArrayToFile
=
fileName array dataType numberOfElements numberOfGroups arrayDataOrder
(char *
int int int
fileName numberOfElements arrayDataOrder fieldWidth
string File pathname.
void * Numeric array.
integer Array element data type.
integer Number of elements in array.
integer Number of groups in array.
integer How groups are ordered in file.
, void *
, int
array
, int
, int
fileLayout
fileType
, int
numberOfGroups
, int
dataType
, int
fileAction);
,
,
colSepStyle
,
fileLayout colSepStyle fieldWidth fileType fileAction
LabWindows/CVI Standard Libraries 2-4 © National Instruments Corporation
integer Direction to write groups in file.
integer How data on one line are separated.
integer Constant width between columns.
integer ASCII/binary mode.
integer File pointer reposition location.
Chapter 2 Formatting and I/O Library
Return Value
status
integer Indicates success/failure.
Return Codes
0 Success.
-1 Error attempting to open file.
-2 Error attempting to close file.
-3 An I/O error occurred.
-4
-5
-6
-7
-8
-9
-10
-11
Invalid dataType parameter. Invalid numberOfElements parameter. Invalid numberOfGroups parameter. Invalid arrayDataOrder parameter. Invalid fileLayout parameter. Invalid fileType parameter. Invalid separationStyle parameter. Invalid fieldWidth parameter.
-12
Invalid fileAction parameter.
Parameter Discussion FileName may be an absolute pathname or a relative file name. If you use a relative file name,
the file is created relative to the current working directory. DataType must be one of the following.
VAL_CHAR VAL_SHORT_INTEGER VAL_INTEGER VAL_FLOAT VAL_DOUBLE VAL_UNSIGNED_SHORT_INTEGER VAL_UNSIGNED_INTEGER VAL_UNSIGNED_CHAR
If you save the array data in ASCII format, you may divide the array data into groups. Groups can be written as either columns or rows. NumberOfGroups specifies the number of groups into which to divide the array data. If you do not want to divide your data into groups, use 1.
If you divide your array data into groups, arrayDataOrder specifies how the data is ordered in the array. The two choices are as follows.
© National Instruments Corporation 2-5 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
VAL_GROUPS_TOGETHER—
all points of each data group are assumed to be stored consecutively
in the data array.
VAL_DATA_MULTIPLEXED
it is assumed that the first point from each data group is stored
together, followed by the second point from each group and so on.
If you save the array data in ASCII format, fileLayout specifies how the data appears in the file. The two choices are as follows.
VAL_GROUPS_AS_COLUMNS
VAL_GROUPS_AS_ROWS
• If you have only one group, use
VAL_GROUPS_AS_COLUMNS
to write each array element on a
separate line. If you specify that multiple values be written on each line, colSepStyle specifies how the values
are separated. The choices are as follows.
VAL_CONST_WIDTH
VAL_SEP_BY_COMMA
VAL_SEP_BY_TAB
constant field width for each column
values followed by commas, except last value on line
values separated by tabs
If you have specified a colSepStyle of
VAL_CONST_WIDTH
, fieldWidth specifies the width of
the columns. FileType specifies whether to create the file in ASCII or binary format. The choices are as follows.
VAL_ASCII
VAL_BINARY
FileAction specifies the location in the file to begin writing data if the named file already exists. The choices are as follows.
VAL_TRUNCATE
—Positions the file pointer to the beginning of the file and deletes its prior
contents.
VAL_APPEND
VAL_OPEN_AS_IS
—All write operations append data to file.
—Positions the file pointer at the beginning of the file but does not
affect the prior file contents.
LabWindows/CVI Standard Libraries 2-6 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

CloseFile

status
int
Purpose
Closes the file associated with the OpenFile function and specifies the file to close.
Parameter
Input
Return Value
status
Return Codes
-1 0
CloseFile (
=
fileHandle
fileHandle);
int
fileHandle
fileHandle
.
integer File handle.
integer Result of the close file
Bad file handle. Success.
is the file handle that was returned from
operation.

CompareBytes

result
int
Purpose
Compares the
numberofBytes Parameters
Input
CompareBytes (
=
numberofBytes
starting at position
char *
int
starting at position
buffer#1 buffer#1Index buffer#2 buffer#2Index numberofBytes caseSensitive
buffer#1,
buffer#2Index,
buffer#2Index
string String 1. integer string String 2. integer integer Number of bytes to compare. integer Case sensitivity mode.
buffer#1Index,
int
numberofBytes,
int
buffer#1Index
buffer#2
of
char *
buffer#1
of
.
Starting position in
Starting position in
buffer#2,
int
to the
caseSensitive);
buffer#1.
buffer#2.
© National Instruments Corporation 2-7 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Return Value
result
integer Result of the compare
operation.
Return Codes
-1 0 1
Bytes from buffer#1 less than bytes from buffer#2. Bytes from buffer#1 identical to bytes from buffer#2. Bytes from buffer#1 greater than bytes from
buffer#2.
Parameter Discussion
Both buffer#1Index and buffer#2Index are zero-based. If caseSensitive is zero, alphabetic characters are compared without regard to case. If
caseSensitive is non-zero, alphabetic characters are considered equal only if they have the same case.
The function returns an integer value indicating the lexicographic relationship between the two sets of bytes.

CompareStrings

int result = CompareStrings (char *string#1, int string#1Index, char *string#2,
int string#2Index, int caseSensitive);
Purpose
Compares the NUL-terminated string starting at position string#1Index of string#1 to the NUL-terminated string starting at position string#2Index of string#2. Both string#1Index and
string#2Index are zero-based. Parameters
Input
string#1 string#1Index string#2 string#2Index caseSensitive
string String 1. integer
Starting position in string#1.
string String 2. integer
Starting position in string#2.
integer Case sensitivity mode.
LabWindows/CVI Standard Libraries 2-8 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Return Value
result
integer Result of the compare
operation.
Return Codes
-1 0 1
Bytes from string#1 less than bytes from string#2. Bytes from string#1 identical to bytes from string#2. Bytes from string#1 greater than bytes from string#2.
Parameter Discussion If caseSensitive is zero, alphabetic characters are compared without regard to case. If
caseSensitive is non-zero, alphabetic characters are equal only if they have the same case.
The function returns an integer value indicating the lexicographic relationship between the two strings.

CopyBytes

void CopyBytes (char targetBuffer[], int targetIndex, char *sourceBuffer,
int sourceIndex, int numberofBytes);
Purpose Copies the numberofBytes bytes starting at position sourceIndex of sourceBuffer to position
targetIndex of targetBuffer. Parameters
Input
targetIndex
integer Starting position in
targetBuffer. sourceBuffer sourceIndex
string Source buffer. integer Starting position in
sourceBuffer.
integer Number of bytes to copy. string Destination buffer.
Output
numberofBytes targetBuffer
Return Value
None
© National Instruments Corporation 2-9 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Parameter Discussion
Both sourceIndex and targetIndex are zero-based. You can use this function even when sourceBuffer and targetBuffer overlap.

CopyString

void CopyString (char targetString[], int targetIndex, char *sourceString,
int sourceIndex, int maximum#Bytes);
Purpose Copies the string starting at position sourceIndex of sourceString to position targetIndex of
targetString until an ASCII NUL is copied or maximum#Bytes bytes have been copied.
Appends an ASCII NUL if no ASCII NUL was copied.
Parameters
Input
targetIndex sourceString sourceIndex maximum#Bytes
integer
Starting position in targetString.
string Source buffer. integer
Starting position in sourceString.
integer Number of bytes to copy, excluding the ASCII
NUL.
Output
targetString
string Destination buffer.
Return Value
None
Parameter Discussion
Both sourceIndex and targetIndex are zero-based. If you want to use maximum#Bytes to prevent from writing beyond the end of targetString, make sure that you allow room for the ASCII NUL. For example, if maximum#Bytes is 40, the destination buffer should contain at least 41 bytes.
If you do not want to specify a maximum number of bytes to copy, use -1 for maximum#Bytes. You can use this function even when sourceString and targetString overlap.
Note: The value of maximum#Bytes must not exceed one less than the number of bytes in
the target variable.
LabWindows/CVI Standard Libraries 2-10 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

FileToArray

int
status
FileToArray
=
(char *
numberOfElements
int
arrayDataOrder
int
fileName
, void *
, int
array
, int
, int
fileLayout
dataType
numberOfGroups
fileType);
, int
Purpose
Reads data from a file into an array. Can be used with files created using the function. The function handles creating, opening, reading, and closing the file.
Parameters
Input
Output
fileName dataType numberOfElements numberOfGroups arrayDataOrder fileLayout fileType array
string File pathname. integer Array element data type. integer Number of elements in array. integer Number of Groups in array. integer How groups are ordered in file. integer Direction to write groups in file. integer ASCII/binary mode. void* Numeric array.
,
,
ArrayToFile
Return Value
status
Return Code
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
integer Indicates success or failure.
Success. Error attempting to open file. Error attempting to close file. An I/O error occurred. Invalid Invalid Invalid Invalid Invalid Invalid
arrayDataType
parameter.
numberOfElements numberOfGroups arrayDataOrder fileLayout fileType
parameter.
parameter.
parameter.
parameter.
parameter.
© National Instruments Corporation 2-11 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Parameter Discussion FileName may be an absolute pathname or a relative file name. If you use a relative file name,
the file is located relative to the current working directory. DataType must be one of the following.
VAL_CHAR
VAL_SHORT_INTEGER
VAL_INTEGER
VAL_FLOAT
VAL_DOUBLE
VAL_UNSIGNED_SHORT_INTEGER
VAL_UNSIGNED_INTEGER
VAL_UNSIGNED_CHAR
NumberOfGroups specifies the number of groups into which the data in the file is divided. Groups can be in the form of either columns or rows. If there are no groups, use 1. This parameter only applies if the file type is ASCII.
If the data is divided into groups, arrayDataOrder specifies the order in which the data is to be stored in the array. The two choices are as follows.
VAL_GROUPS_TOGETHER— all points from one data group are stored together followed by all points from the next data group.
VAL_DATA_MULTIPLEXED—the first points from each data group are stored consecutively, followed by the second points from each group, etc.
If the file is in ASCII format, fileLayout specifies how the data appears in the file. The two choices are as follows.
VAL_GROUPS_AS_COLUMNS
VAL_GROUPS_AS_ROWS
If there is only one group, VAL_GROUPS_AS_COLUMNS specifies that each value in the file is on a separate line.
FileType specifies whether the file is in ASCII or binary format. The choices are as follows.
VAL_ASCII
VAL_BINARY
LabWindows/CVI Standard Libraries 2-12 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

FillBytes

void
Purpose
Sets the lower byte of
Parameters
Return Value
FillBytes (
numberofBytes
Input
None

FindPattern

char
value
buffer startingIndex numberofBytes value
buffer[],
bytes starting at position
startingIndex
.
int
startingIndex,
is zero-based.
string Destination buffer. integer integer Number of bytes to fill. integer Value to place in bytes.
int
startingIndex
numberofBytes,
buffer
of
Starting position in
value);
int
to the value in the
buffer
.
ndx
int
Purpose
Searches a character buffer for a pattern of bytes. The pattern of bytes is specified by the string
pattern Parameters
Input
FindPattern (
=
.
char *
char *
buffer startingIndex numberofBytes pattern caseSensitive startFromRight
buffer,
pattern,
string Buffer to be searched. integer integer Number of bytes to search. string Pattern to search for. integer Case-sensitivity mode. integer Direction of search.
startingIndex,
int
caseSensitive,
int
numberofBytes,
int
startFromRight);
int
Starting position in
buffer
.
© National Instruments Corporation 2-13 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Return Value
ndx
integer
Index in buffer where pattern was found.
Return Code
-1
Pattern not found.
Parameter Discussion The buffer searched is the set of numberofBytes bytes starting at position startingIndex of
buffer. Exception: If numberofBytes is -1, the buffer searched is the set of bytes starting at
position startingIndex of buffer up to the first ASCII NUL. startingIndex is zero-based. If caseSensitive is zero, alphabetic characters are compared without regard to case. If
caseSensitive is non-zero, alphabetic characters are considered equal only if they have the same case. If startFromRight is zero, the leftmost occurrence of the pattern in the buffer will be found. If startFromRight is non-zero, the rightmost occurrence of the pattern in the buffer will be found.
If the pattern is found, pattern returns the index relative to the beginning of buffer where it found the first byte of the pattern. If the pattern is not found, pattern returns -1.
The following example returns 4, which is the index of the second of the three occurrences of in the string
1ab2ab3ab4
. The first occurrence is skipped because startingIndex is 3. Of the
two remaining occurrences, the leftmost is found because startFromRight is zero:
ndx = FindPattern ("1ab2ab3ab4", 3, -1, "AB", 0, 0);
On the other hand, the following line returns 7, which is the index of the last occurrence of
ab
because startFromRight is non-zero:
ndx = FindPattern ("1ab2ab3ab4", 3, -1, "AB", 0, 1);
Fmt
int
n = Fmt (
Purpose
Formats the source1 ... sourcen arguments according to descriptions in the formatString argument.
void
*target,
char
*formatString, source1,...,sourcen);
ab
,
LabWindows/CVI Standard Libraries 2-14 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Parameters
Input
formatString
String.
source1,…,sourcen Types must match formatString contents.
Output
target Type must match formatString contents.
Return Value
n
integer Number of source format
specifiers satisfied.
Return Code
-1
Format string error.
Using This Function
This function places the result of the formatting into the target argument, which you must pass by reference. The return value indicates how many source format specifiers were satisfied, or
-1 if the format string is in error. A complete discussion of this function is in the Using the
Formatting and Scanning Functions section later in this chapter.

FmtFile

int n = FmtFile (int fileHandle, char *formatString, source1,…,sourcen); Purpose
Formats the source1 ... sourcen arguments according to descriptions in the formatString argument. The result of the formatting is written into the file corresponding to the fileHandle argument, which was obtained by a call to the LabWindows/CVI function OpenFile.
Parameters
Input
fileHandle formatString source1,…,sourcen types must match formatString
integer File handle. string
contents
© National Instruments Corporation 2-15 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Return Value
n
integer Number of source format
specifiers satisfied.
Return Codes
-1
-2
Format string error I/O error.
Using This Function
The return value indicates how many source format specifiers were satisfied, -1 if the format string is in error, or -2 if there was an I/O error. A complete discussion of this function is in the Using the Formatting and Scanning Functions section later in this chapter.

FmtOut

int n = FmtOut (char *formatString, source1,…,sourcen); Purpose
Formats the source1 ... sourcen arguments according to descriptions in the formatString argument. The result of the formatting is written to the Standard I/O window.
Parameters
Input
formatString
String.
source1,…,sourcen Types must match formatString contents.
Return Value
n
integer Number of source format
specifiers satisfied.
Return Codes
-1
-2
Format string error. I/O error.
LabWindows/CVI Standard Libraries 2-16 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Using This Function
The return value indicates how many source format specifiers were satisfied, -1 if the format string is in error, or -2 if there was an I/O error. A complete discussion of this function is in the Using the Formatting and Scanning Functions section later in this chapter.

GetFileInfo

int status = GetFileInfo (char *fileName, long *fileSize); Purpose
Verifies if a file exists. Returns an integer value of zero if no file is present and 1 if file is present. fileSize is a long variable that contains the file size in bytes or zero if no file exists.
Parameters
Input
fileName
string Pathname of the file to be
checked.
Output
fileSize
long File size or zero.
Return Value
status
integer Indicates if the file exists.
Return Codes
1 0
-1
File exists. File does not exist. Maximum number of files already open.
Example
/* Check for presence of file A:\DATA\TEST1.DAT. */ /* Print its size */ /* if file exists or message stating file does not exist. */ int n; long size; n = GetFileInfo("a:\\data\\test1.dat",&size); if (n == 0)
FmtOut("File does not exist.");
else
FmtOut("File size = %i[b4]",size);
© National Instruments Corporation 2-17 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2

GetFmtErrNdx

int n =
GetFmtErrNdx (
void
);
Purpose
Returns the zero-based index into the format string where an error occurred in the last formatting or scanning call.
Parameters
None
Return Value
n
integer Position of error in format
string.
Return Code
-1
No error.
Using This Function
If the format string of the preceding call contains an error, such as an invalid format, or inappropriate modifier, the return value indicates the position within the format string, beginning with position zero, where the error was found. The function can report only one error per call, even if several errors existed within the string.
Example
int i, n; Scan ("1234", "%s>%d", &i); n = GetFmtErrNdx (); /* n will have the value -1, indicating that */ /* there was no error found in the format string. */

GetFmtIOError

status = GetFmtIOError
int
Purpose
This function returns specific I/O information for the last call to a Formatting and I/O function that performs file I/O. If the last function was successful,
(void);
GetLastFmtIOError
returns zero (no
LabWindows/CVI Standard Libraries 2-18 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
error). If the last function that performs I/O encountered an I/O error, GetLastFmtIOError returns a nonzero value.
Return Value
status integer Indicates success or failure of last function that
performed file I/O.
Return Codes
FmtIONoErr FmtIONoFileErr FmtIOGenErr FmtIOBadHandleErr FmtIOInsuffMemErr FmtIOFileExistsErr FmtIOAccessErr FmtIOInvalArgErr FmtIOMaxFilesErr FmtIODiskFullErr FmtIONameTooLongErr
0 No error. 1 File not found. 2 General I/O error. 3 Invalid file handle. 4 Not enough memory. 5 File already exists. 6 Permission denied. 7 Invalid argument. 8 Maximum number of files open. 9 Disk is full. 10 File name is too long.

GetFmtIOErrorString

char *message = GetFmtIOErrorString (int errorNum); Purpose Converts the error number returned by GetLastFmtIOError into a meaningful error message. Parameters
Input
errorNum
integer
Error Code returned by GetLastFmtIOErr.
Return Value
message
© National Instruments Corporation 2-19 LabWindows/CVI Standard Libraries
string Explanation of error.
Formatting and I/O Library Chapter 2

NumFmtdBytes

int n =
NumFmtdBytes (
void
);
Purpose
Returns the number of bytes formatted or scanned by the previous formatting or scanning call.
Parameters
None
Return Value
n
integer Number of bytes formatted or
scanned.
Using This Function
If the previous call was a formatting call, NumFmtdBytes returns the number of bytes placed into the target. If the previous call was a scanning call, NumFmtdBytes returns the number of bytes scanned from the source. The return value is undefined if there have been no preceding formatting or scanning calls.
Certain operations using the FmtFile and ScanFile routines can result in more than 64 KB being formatted or scanned. Because NumFmtdBytes returns an integer, its value will not be accurate in these cases. The value returned rolls over when formatting or scanning more than 65,535 bytes.
Example
double f; int n; Scan ("3.1416", "%s>%f", &f); n = NumFmtdBytes (); /* n will have the value 6, indicating that six bytes */ /* were scanned from the source string. */

OpenFile

handle
int
Purpose
Opens a file for input and/or output.
OpenFile (
=
char *
fileName,
read/writeMode,
int
int
action,
int
fileType);
LabWindows/CVI Standard Libraries 2-20 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Parameters
Input
fileName read/writeMode action fileType
string Pathname. integer Read/write mode. integer File pointer reposition location. integer ASCII/binary mode.
Return Value
handle
integer File handle to be used in
subsequent ReadFile/WriteFile calls.
Return Code
-1
Function failed, unable to open file, or bad argument to function.
Parameter Discussion fileName is a pathname specifying the file to be opened. If the read/writeMode argument is
write or read/write, this function creates the file if it does not already exist. If a file is created, it is created with no protection; that is, both reading and writing can be performed on it. Use the function
GetFileInfo
if it is necessary to determine whether a file already exists.
read/writeMode specifies how the file is opened:
VAL_READ_WRITE =
VAL_READ_ONLY =
VAL_WRITE_ONLY =
open file for reading and writing
open file for reading only
open file for writing only
action specifies whether to delete the old contents of the file, and whether to force the file pointer to the end of the file before each write operation. action is meaningful only if read/writeMode = write or read/write. After read operations are performed, the file pointer points to the byte following the last byte read. action values are as follows:
VAL_TRUNCATE =
truncate file (deletes its old contents and positions the file pointer at the
beginning of the file.
VAL_APPEND =
VAL_OPEN_AS_IS =
do not truncate file (all write operations append to end of file).
do not truncate file (positions the file pointer at the beginning of the
file. )
© National Instruments Corporation 2-21 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
fileType specifies whether to treat file as ASCII or binary. When performing I/O on a file in binary mode, no special treatment is given to carriage returns (CR) and line feeds (LF). When you open the file in ASCII mode, CR LF combination translates to LF when reading, and LF translates to CR LF when writing. fileType values are as follows:
VAL_BINARY = binary
VAL_ASCII = ASCII

ReadFile

int n = ReadFile (int fileHandle, char buffer[], int count); Purpose
Reads up to count bytes of data from a file or STDIN into buffer. Reading starts at the current position of the file pointer. When the function completes, the file pointer points to the next unread character in the file.
Parameters
Input
Output
fileHandle count buffer
integer File handle. integer Number of bytes to read. string Input buffer.
Return Value
n
integer Number of bytes read.
Return Codes
-1 0
Error, possibly bad handle. Tried to read past end-of-file.
Parameter Discussion fileHandle is the file handle returned by the OpenFile function. fileHandle points to the file
from which you want to read. If fileHandle =0, input is read from STDIN, and no prior OpenFile call is needed. buffer is the buffer into which you read data. You must allocate
space for this buffer before you call this function. count specifies the number of bytes to read. count must not be greater than buffer size.
LabWindows/CVI Standard Libraries 2-22 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Using This Function
The return value can be less than number of bytes requested if end of file was reached before byte count was satisfied. Notice that if you open the file in ASCII mode, each CR LF combination read is counted as 1 character, because the pair is translated into LF when stored in the buffer.
Note: This function does not terminate the buffer with an ASCII NUL.

ReadLine

int n = ReadLine (int fileHandle, char lineBuffer[], int maximum#Bytes); Purpose
Reads bytes from a file until a linefeed is encountered.
Parameters
Input
fileHandle maximum#Bytes
Output
lineBuffer
Return Value
n
Return Codes
-2
-1
Parameter Discussion
integer File handle. integer Maximum number of bytes to
read into line, excluding the ASCII NUL.
string Input buffer.
integer Number of bytes read,
excluding linefeed.
End of file. I/O error.
This function places up to maximum#Bytes bytes, excluding the linefeed, into lineBuffer. Appends an ASCII NUL to lineBuffer. If there are more than maximum#Bytes bytes before the linefeed, the extra bytes are discarded.
fileHandle is the file handle that was returned from the OpenFile function and specifies the file from which to read the line. The file should be opened in ASCII mode so that a
© National Instruments Corporation 2-23 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
carriage-return/linefeed combination will be treated as a linefeed. If fileHandle is zero, the line will be read from the standard input.
lineBuffer is a character buffer. It should be large enough to contain maximum#Bytes bytes plus an ASCII NUL.
ReadLine returns the number of bytes read from the file, including discarded bytes, but excluding the linefeed. Hence, the return value will exceed maximum#Bytes if and only if bytes are discarded.
If no bytes are read because the end of the file has been reached, ReadLine returns -2. If an I/O error occurs, ReadLine returns -1.

Scan

int n = Scan (void *source, char *formatString, targetptr1,…,targetptrn); Purpose
Scans a single source item in memory and breaks it into component parts according to format specifiers found in a formatString. The components are then placed into the target parameters.
Parameters
Input
Output
source Type must match formatString contents formatString
string.
targetptr1,…,targetptrn Types must match formatString contents.
Return Value
n
integer Number of target format
specifiers satisfied.
Return Code
-1
Format string error.
Using This Function
The return value indicates how many target format specifiers were satisfied, or -1 if the format string is in error. A complete discussion of this function is in the Using the Formatting and
Scanning Functions section later in this chapter.
LabWindows/CVI Standard Libraries 2-24 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

ScanFile

int n =
ScanFile (
int
fileHandle,
char *
formatString, targetptr1
targetptrn);
,…,
Purpose
Performs the same basic operation as the Scan function, except that the source material is obtained from the file referred to by the
fileHandle
argument, which is obtained by calling the
LabWindows/CVI function OpenFile.
Parameters
Input
Output
fileHandle formatString targetptr1,…,targetptrn
Integer. String. Types must match
formatString
contents.
Return Value
n
integer Number of target format
specifiers satisfied.
Return Codes
-1
-2
Format string error. I/O error.
Using This Function
The amount of data read from the file depends on the amount needed to fulfill the formats in the format string. The return value indicates how many target format specifiers were satisfied, -1 if the format string is in error, or -2 if there was an I/O error. A complete discussion of this function is in the Using the Formatting and Scanning Functions section later in this chapter.

ScanIn

int n =
ScanIn (
char *
Purpose
Performs the same basic operation as the ScanFile function, except that the source material is obtained from STDIN.
formatString, targetptr1
targetptrn);
,…,
© National Instruments Corporation 2-25 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Parameters
Input Output
formatString targetptr1,…,targetptrn Types must match formatString contents.
String.
Return Value
n
integer Number of target format
specifiers satisfied.
Return Codes
-1
-2
Format string error. I/O error.
Using This Function
No argument is required for the source item in the case of the
ScanIn
function. The return value indicates how many target format specifiers were satisfied, -1 if the format string is in error, or -2 if there was an I/O error. A complete discussion of this function is in the Using the Formatting and Scanning Functions section later in this chapter.

SetFilePtr

long
position = SetFilePtr ( Purpose Moves the file pointer for the file specified by fileHandle to a location that is offset bytes from
origin. Returns the offset of the new file pointer position from the beginning of the file. Parameters
Input
fileHandle
offset
origin
int
fileHandle,
long
offset,
int
origin);
integer File handle returned by
OpenFile
.
long integer Number of bytes from origin to
position of file pointer.
integer Position in file from which to
base offset.
LabWindows/CVI Standard Libraries 2-26 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Return Value
position
long integer Offset of the new file pointer
Return Code
-1
Error due to an invalid file handle, an invalid origin value, or an offset value that is before the beginning of the file.
Parameter Discussion The valid values of origin are as follows:
0 =
beginning of file
1 =
current position of file pointer
2 =
end of file
Using This Function
position from the beginning of the file.
This function can also be used to obtain the file size by setting offset to 0 and origin to 2. In this case, the return value indicates the file size and the pointer will be at the end of the file.
It is possible to position the file pointer beyond the end of the file. Intermediate bytes (bytes between the old end of file and the new end of file) contain indeterminate values. An attempt to position the file pointer before the beginning of the file causes the function to return an error.
If the file is a device that does not support random access (such as the standard input), the function returns an indeterminate value.
Example
/* Open or create the file c:\TEST.DAT, move 10 bytes into the
file, and write a string to the file. */ /* Note: Use \\ in pathname in C instead of \. */ int handle,result; long position; handle = OpenFile("c:\\TEST.DAT", 0, 2, 1); if (handle == -1){
FmtOut("error opening file");
exit(1); } position = SetFilePtr(handle, 10L, 0); if (position == 10){
© National Instruments Corporation 2-27 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
result = WriteFile(handle, "Hello, World!", 13);
if (result == -1)
FmtOut("error writing to file"); } else
FmtOut("error positioning file pointer");
CloseFile(handle);

StringLength

int
StringLength (
n =
char
string);
*
Purpose
Returns the number of bytes in the
Parameter
Input
string
Return Value
n
Example
char s[100]; int nbytes; nbytes = StringLength (s);
string
String.
integer
before the first ASCII NUL.
Number of bytes in before ASCII NUL.
string

StringLowerCase

void
StringLowerCase (
char
Purpose
Converts all uppercase alphabetic characters in the NUL-terminated
Parameter
Input/Output
LabWindows/CVI Standard Libraries 2-28 © National Instruments Corporation
string
string[]);
String.
string
to lowercase.
Chapter 2 Formatting and I/O Library
Return Value
None

StringUpperCase

void StringUpperCase (char string[]); Purpose Converts all lowercase alphabetic characters in the NUL-terminated string to uppercase. Parameter
Input/Output
Return Value
None
string
String.

WriteFile

int n = WriteFile (int fileHandle, char *buffer, unsigned int count); Purpose
Writes up to count bytes of data from buffer to a file or to STDOUT. Writing starts at the current position of the file pointer, and when the function completes, the file pointer is incremented by the number of bytes written.
Parameters
Input
fileHandle
integer File handle.
buffer count
Return Value
n
© National Instruments Corporation 2-29 LabWindows/CVI Standard Libraries
string Data buffer. integer Number of bytes to write.
integer Number of bytes written to the
file.
Formatting and I/O Library Chapter 2
Return Code
-1
Error.
Parameter Discussion fileHandle is the file handle that was returned from the OpenFile function. If fileHandle=1,
data is written to STDOUT and no prior OpenFile call is needed.
buffer is the buffer from which to write data. count specifies number of bytes to write. The count parameter overrides the buffer size in
determining the number of bytes to write. Buffers containing embedded NUL bytes are written in full. count must not be greater than buffer size.
Using This Function
For files opened in ASCII mode, each LF character is replaced with a CR-LF combination in the output. In this case, the return value does not include the CR character written to the output.
An error can indicate a bad file handle, an attempt to access a protected file, an attempt to write to a file opened as ReadOnly, or no more space left on disk.

WriteLine

int n = WriteLine (int fileHandle, char *lineBuffer, int numberofBytes); Purpose Writes numberofBytes bytes from lineBuffer to a file and then writes a linefeed to the file. Parameters
Input
Return Value
n
fileHandle lineBuffer numberofBytes
integer File handle. string Data buffer. integer Number of bytes to write.
integer Number of bytes written.
including line feed.
LabWindows/CVI Standard Libraries 2-30 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Return Code
-1
Parameter Discussion
If numberofBytes is -1, only the bytes in lineBuffer before the first ASCII NUL are written, followed by a linefeed.
fileHandle is the file handle that was returned from the opened in ASCII mode so that a carriage return will be written before the linefeed. If fileHandle is 1, the line will be written to the
Using This Function
WriteLine
error occurs,
returns the number of bytes written to the file, excluding the linefeed. If an I/O
WriteLine
returns -1.
I/O error.
STDOUT
OpenFile
.
function. The file should be

Using the Formatting and Scanning Functions

You use data formatting functions to translate or reformat data items into other forms. Typical usages might be to translate between data stored on external files and the internal forms which the program can manipulate, or to reformat a foreign binary representation into one on which the program can operate.
There are three subclasses of data formatting functions in the LabWindows/CVI Formatting and I/O Library:
Formatting functions
Scanning functions
Status functions You use formatting functions to combine and format one or more source items into a single
target item, and you use scanning functions to break apart a single source item into several target items. The status functions return information regarding the success or failure of the formatting or scanning functions.

Introductory Formatting and Scanning Examples

To introduce you to the formatting and scanning functions, consider the following examples.
© National Instruments Corporation 2-31 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Convert the integer value 23 to its ASCII representation and place the contents in a string variable:
char a[5]; int b,n; b = 23; n = Fmt (a, "%s<%i", b);
After the In this example, a is the target argument, b is the source argument, and the string
format string. The
Fmt
call, a contains the string 23.
Fmt
call uses the format string to determine how to convert the source
%s<%i
is the
argument into the target argument. With the
After the In this example, a is the source argument, b is the target argument, and
Scan
function, you can convert the string 23 to an integer:
char *a; a = "23"; n = Scan (a$, "%s>%i", b%);
Scan
call, b = 23.
%s>%i
is the format string. In both the formatting and the scanning functions, the format string defines the variable types of the source and target arguments and the method by which the source arguments are transformed into the target arguments.

Formatting Functions

The following information is a brief description of the three formatting functions:
n = Fmt (target, formatstring, source1, ..., sourcen);
Fmt
The descriptions in the formatting into the
n = FmtFile (handle, formatstring, source1, ..., sourcen);
The descriptions in the
function formats the
formatstring
target
FmtFile
function formats the
formatstring
formatting into the file corresponding to the
n = FmtOut (formatstring, source1, ..., sourcen);
FmtOut
The descriptions in the
function formats the
formatstring
source1, ..., sourcen
argument. The function places the result of the
argument.
source1, ..., sourcen
argument. The function writes the result of the
handle
argument.
source1, ..., sourcen
argument. The function writes the result of the
arguments according to
arguments according to
arguments according to
formatting to Standard Out.
LabWindows/CVI Standard Libraries 2-32 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Each of these formatting functions return the number of source format specifiers satisfied. If there is an error in the format string, -1 is returned.
The formatting functions are used to format and combine multiple source items into a single target item. The only difference in the workings of the three functions is the location of the target data. For the function Fmt, the target is a data item in memory which is passed to the function by reference. For FmtFile, the target is a file whose handle is passed as the first argument. The LabWindows/CVI function OpenFile returns this handle. For the function FmtOut, the target is Standard Out (typically the display), and in this case the target argument present in the other two functions is omitted. Except for these differences, the following descriptions apply to all the formatting functions.
The target parameter for Fmt must be passed by reference (that is, must be a pointer).

Formatting Functions—Format String

Consider the following formatting function:
n = Fmt(target, formatstring, source1, ..., sourcen);
where formatstring contains the information to transform the source arguments to the target argument.
Format strings for all the formatting functions are of the form:
"target_spec < source_specs_and_literals"
where target_spec is a format specifier that describes the nature of the target data item, and source_specs_and_literals is a sequence of format specifiers and literal characters that
indicate how the source material is to be combined into the target. Examples of format strings for the formatting functions are as follows.
"%s < RANGE %i"
"%s < %s; %i"
The character < is a visual reminder of the direction of the data transformation (that is, from the sources to the target), and also separates the single target format specifier from the (perhaps multiple) source format specifiers and literals. The target format specifier can be omitted, in which case a %s string format is assumed. If the target format specifier is omitted, the < character can be omitted also, or retained for clarity.
Notice that the target format specifier is located to the left of the < symbol, just as the target parameter is located to the left of the format string. Likewise, the source format specifiers are located to the right of the < symbol, just as the source parameters are located to the right of the format string.
© National Instruments Corporation 2-33 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Format specifiers describe the inputs and outputs of data transformations. Each format specifier has the following form.
% [ rep ] formatcode [[ modifiers ]]
The character % introduces all format specifiers. repeats with respect to the arguments. nature of the data items being formatted.
formatcode
modifiers
of codes which further describe the data format. Examples of format specifiers are as follows.
%s %100f %i[b2u]
Note:
rep
is not allowed when
formatcode
s
string. As a source or target specifier, this indicates that the corresponding parameter is a
is specified with one of the following codes:
formatcode
character string. As a target specifier (the default if no target specifier is present), this can mean that numeric source parameters become converted into an ASCII form for inclusion in the target string. See the individual numeric formats, such as %i and %f, for details of these conversions. Arrays of strings are not allowed. For example, a valid format string.
Note: When a target string is filled in, an ASCII NUL is always placed in the string
after the last byte.
rep
indicates how many times the format
is a code character which indicates the
is an optional bracket-enclosed sequence
is s (string).
%10s
is not
i
integer. This source or target specifier indicates that the corresponding parameter is an integer or, if
rep
is present, an integer array. The function performs conversions to ASCII digits when converting to or from the string format %s. A modifier is available to specify the radix to be used in such a conversion (default is decimal).
x
integer (hexadecimal). This source or target specifier indicates that the corresponding parameter is an integer or, if conversions to ASCII hexadecimal digits (
rep
is present, an integer array. The function performs
0123456789abcdef
) when converting to or
from the string format %s.
o
integer (octal). This source or target specifier indicates that the corresponding parameter is an integer or, if ASCII octal digits (
d
integer (decimal). This format specifier is identical to %i and is included for compatibility with the C
rep
is present, an integer array. The function performs conversions to
01234567
printf
) when converting to or from the string format %s.
family of functions.
LabWindows/CVI Standard Libraries 2-34 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
f real number. This source or target specifier indicates that the corresponding parameter is
a real number, or if rep is present, a real array. The function performs conversions to ASCII when converting to or from the string format %s.
c character. This source or target specifier indicates that the corresponding parameter is an
integer with one significant byte, or, if rep is present, an array of 1-byte integers. The function does not perform conversion to ASCII when converting to or from the string format %s. The byte is copied directly to or from the string.

Formatting Modifiers

modifiers are optional codes used to describe the nature of the source or target data. If you use them, you must enclose the modifiers in square brackets and place them immediately after the format code they modify. If one format specifier requires more than one modifier, enclose all modifiers in the same set of brackets.
There is a different set of modifiers for each possible format specifier.

Formatting Integer Modifiers (%i, %d, %x, %o, %c)

bn Specify Length. The b integer modifier specifies the length of the integer
argument, or the length of an individual integer array element, in bytes. The default length is 4 B; therefore, simple 4 B integers do not need this modifier. The modifier b2 represents short integers. The modifier b1 represents single-byte integers.
in Specify Array Offset. The i integer modifier specifies an offset within an
integer array argument. It indicates the location within the array where processing begins. n is the zero-based index of the first element to process. Thus, %10d[i2] applied to a source integer array reads the 10 integer values from the third through the twelfth elements of the array. The i modifier is valid only if rep is present. If you use the i modifier with the z modifier, then n is in terms of bytes.
z Treat String as Integer Array. The z integer modifier indicates that the data
type of the corresponding argument is a string. Nevertheless, the data in the string is treated as an integer array. The z modifier is valid only if rep is present.
rn Specify Radix. The r integer modifier specifies the radix of the integer
argument, which is important if the integer was to be converted into string format. Legal radixes are 8 (octal), 10 (decimal, the default), 16 (hexadecimal), and 256 (a special radix representing single 8-bit ASCII characters).
wn Specify String Size. The w integer modifier specifies the exact number of bytes
in which to store a string representation of the integer argument, in the event that
© National Instruments Corporation 2-35 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
the integer is converted to a string format. You can enter any non-negative value here. If n is less than the number of digits required to represent the integer, an asterisk (*) will be inserted into the string to signify an overflow. The default for
n is zero, which indicates that the integer can occupy whatever space is necessary.
pc Specify Padding. The p integer modifier specifies a padding character c, which
fills the space to the left of an integer in the event it does not require the entire width specified with the wn modifier. The default padding character is a blank.
s Specify as Two’s Complement. The s integer modifier indicates that the integer
argument is considered a signed two's complement number. This is the default interpretation of integers, so the s modifier is never explicitly required.
u Specify as Unsigned. The u integer modifier indicates that the integer is
considered an unsigned integer.
onnnn Specify Byte Ordering. The o integer modifier is used to describe the byte
ordering of raw data so that LabWindows/CVI can map it to the byte order appropriate for the Intel (PC) or Motorola (SPARCstation) architecture. The number of n's must be equal to the byte size of the integer argument as specified by the bn modifier, which must precede the o modifier. In the case of a four-byte integer, o0123 indicates that the bytes are in ascending order of precedence (Intel style), and o3210 indicates that the bytes are in descending order of precedence (Motorola style).
In a Fmt function, the buffer containing the raw instrument data should have the o modifier describing the byte ordering. The buffer without the o modifier is guaranteed to be in the mode of the host processor. In other words, LabWindows/CVI will reverse the byte ordering of the buffer without the o modifier depending on which architecture the program is running on.
For example, if your GPIB instrument sends two-byte binary data in Intel byte order, your code should appear as follows:
short int instr_buf[100]; short int prog_buf[100]; status = ibrd (ud, instr_buf, 200); Fmt (prog_buf, "%100d<%100d[b2o01]", instr_buf);
If, instead, your GPIB instrument sends two-byte binary data in Motorola byte order, the Fmt function should appear as follows:
Fmt (prog_buf, "%100d<%100d[b2o10]", prog_buf);
In either case, the o modifier is used only on the buffer containing the raw data from the instrument (instr_buf). LabWindows/CVI will ensure that the program buffer (prog_buf) is in the proper byte order for the host processor.
LabWindows/CVI Standard Libraries 2-36 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Note: When using both the bn and on modifiers on an integer specifier, the bn modifier
must be first.

Formatting Floating-Point Modifiers (%f)

bn Specify Length. The b floating-point modifier specifies the length of the
floating-point argument, or the length of an individual array element, in bytes. The default length is 8 bytes; therefore, double-precision values do not need this modifier. Single-precision floating-point values are indicated by b4. 8 and 4 are the only valid values for n.
in
Specify Array Offset. You use the i modifier to specify an offset within a floating-point array argument. It indicates the location within the array where processing is to begin. n is the zero-based index of the first element to process. Thus, %10f[i2] applied to a source floating-point array reads the 10 floating-point values from the third through the twelfth elements of the array. The i modifier is valid only if rep is present. If the i modifier is used with the z modifier, then n is in terms of bytes.
z Treat String as Floating-Point Array. The z floating-point modifier indicates that
the data type of the corresponding argument is a string. Nevertheless, the data in the string is treated as a floating-point array. The z modifier is valid only if rep is present.
wn Specify String Size. The w floating-point modifier specifies the exact number of
bytes in which to store a string representation of the floating-point argument, in the event that the value is converted to a string format. Any non-negative value can be entered here. If n is less than the number of digits required to represent the floating-point number, an asterisk (*) will be inserted into the string to signify an overflow. The default for n is zero, which indicates that the value can occupy whatever space is necessary.
pn Specify Precision. The p floating-point modifier specifies the number of digits to the
right of the decimal point in a string representation of the floating-point number. You can lose significant digits by attempting to conform to the precision specification. If the pn modifier is omitted, the default value is p6.
en Specify as Scientific Notation. The e floating-point modifier specifies that a value
be converted to string format in scientific notation. If omitted, floating-point notation is used. n is optional and specifies the number of digits in the exponent. For example, %f[e2] formats 10.0 as 1.0e+01. If n is omitted, a default of three is used.
f Specify as Floating-Point Notation. The f floating-point modifier specifies the
value to be converted to string format in floating-point notation. This is the default.
© National Instruments Corporation 2-37 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
t Truncate. The t floating-point modifier indicates that in floating-point to integer
transformations, the floating-point value is truncated instead of rounded. This is the default.
r Round. The r floating-point modifier indicates that in floating-point to integer
transformations, the floating-point value is rounded instead of truncated. The default method is truncation.
Note: The value can be represented in scientific notation even when the e modifier is absent.
This occurs when the absolute value of the argument is greater than 1.0e40 or less than 1.0e-40, or when the absolute value of the argument is greater than 1.0e20 or less than 1.0e-4 and neither the p modifier nor the w modifier is present.

Formatting String Modifiers (%s)

in Specify Array Offset. The i string modifier specifies an offset within a string. It
indicates the location within the string where processing is to begin. n is the zero­based index of the first byte to process. Thus, %s[i2] applied to a target string begins placing data in the third byte of the string.
a Append. When applied to a target format specifier, the a string modifier specifies
that all formatted data be appended to the target string. The data is appended beginning at the first occurrence of an ASCII NUL in the target string.
wn Specify String Size. When modifying a source format specifier, the w string modifier
specifies the maximum number of bytes to be consumed from the string argument. You can enter any non-negative value here, the default being zero, which indicates that the entire string should be consumed.
When modifying a target format specifier, the w string modifier specifies the exact number of bytes to store in the string, excluding the terminating ASCII NUL. If n is zero or omitted, as many bytes are stored as are called for by the sources. When n is greater than the number of bytes available from the source, the remaining bytes are filled with ASCII NULs if the q modifier is used, or blanks if the q modifier is not present.
When the w string modifier is used in conjunction with the a string modifier,
n
indicates the number of bytes to append to the string excluding the terminating ASCII NUL.
If wn modifies a target string and n is larger than the number of bytes in the target argument, the target string is overwritten in compiled C.
q Append NULs. When applied to a target string in conjunction with the w string
modifier, the q string modifier specifies that unfilled bytes at the end of the target string be set to ASCII NULs instead of blanks.
LabWindows/CVI Standard Libraries 2-38 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
tn Terminate on Character. When applied to a source string, the t string modifier
specifies that the source string is terminated on the first occurrence of the character n, where n is the ASCII value of the character. Thus, %s[t44] causes reading of the source string to stop on an ASCII comma. Using %s[t44] and the source string
Hello, World! as an example, Hello is placed into the target. More than one t modifier can occur in the same specifier, in which case the string terminates when
any of the terminators occur. If no t modifier is present, reading of the source string stops on an ASCII NUL. This modifier has no effect when applied to the target specifier.
t- Terminate when Full. This is similar to tn, except that it specifies that there are no
terminating characters. Reading of the source string terminates when the target is full or when the number of bytes specified with the w modifier have been read.
t# Terminate on Number. This is equivalent to repeating the t modifier with the
ASCII values of the characters +, -, and 0 through 9. It specifies that reading of the source string be terminated upon occurrence of a numeric expression. Using %s[t#] with the source string ab567, ab is placed in the target.

Fmt, FmtFile, FmtOut—Asterisks (*) Instead of Constants in Format Specifiers

Often, one or more integer values are required in a format specifier. The format specifier for an integer array, for example, requires the number of elements (rep). You can use constants for these integer values in format specifiers. Alternatively, you can specify an integer value using an argument in the argument list. When you use this method, substitute an asterisk (*) for the constant in the format specifier.
You can use the asterisk in the following format specifier elements:
rep For integer or floating-point arrays in For integer or floating-point arrays, or strings wn For any format specifier pn For floating-point specifiers only en For floating-point specifiers only rn For integer specifiers only
When you use one or more asterisks instead of constants in a target specifier, the arguments corresponding to the asterisks must appear after the format string in the same order as their corresponding asterisks appear in the format specifier.
When you use one or more asterisks instead of constants in a source specifier, the arguments corresponding to the asterisks must precede the source argument and must be in the same order as their corresponding asterisks in the format specifier.
© National Instruments Corporation 2-39 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2

Fmt, FmtFile, FmtOut—Literals in the Format String

Literal characters appearing in a formatting function format string indicate that the literal characters are to be combined with the source parameters in the appropriate positions. They do not correspond to any source parameters, but are copied directly into the target item.
Since the left side of the < symbol must be a single format specifier, literal characters if present must be on the right side of the symbol. Literals on the left side or more than one format specifier on the left side result in a -1 error, indicating a faulty format string. You then can use the function GetFmtErrNdx to determine exactly where the error lies in the format string.
The characters %, [, ], <, and > have special meaning in the format strings. To specify that these characters be taken literally, they should be preceded by %.

Scanning Functions

The following information is a brief description of the three scanning functions.
n = Scan (source, formatstring, targetptr1, ..., targetptrn);
The Scan function inspects the source argument and applies transformations to it according to descriptions in the formatstring argument. The results of the transformations are placed into the targetptr1 ... targetptrn arguments.
n = ScanFile (handle, formatstring, targetptr1, ..., targetptrn);
The ScanFile function reads data from the file corresponding to the handle argument and applies transformations to it according to descriptions in the formatstring argument. The results of the transformations are placed into the targetptr1 ... targetptrn arguments.
n = ScanIn (formatstring, targetptr1, ..., targetptrn);
The ScanIn function reads data from standard input and applies transformations to it according to descriptions in the formatstring argument. The results of the transformations are placed into the targetptr1 ... targetptrn arguments.
All of the above functions return the number of target format specifiers satisfied. The function returns a -1 if there is an error in the format string.
The scanning functions break apart a source item into component parts and store the parts into parameters passed to the function. The only difference between the three functions is the location of the source data. For the function Scan, the source item is a data item in memory which is passed to the function. For ScanFile, the source item is a file, whose handle is passed as the first argument. The handle is obtained by a call to the LabWindows/CVI function OpenFile. For the function ScanIn, the source is taken from Standard In (typically the keyboard), and the source argument present in the other two functions is omitted.
All target parameters must be passed by reference.
LabWindows/CVI Standard Libraries 2-40 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

Scanning Functions—Format String

Consider the following scanning function:
n = Scan(source, formatstring, targetptr1, ..., targetptrn);
where
formatstring
targetptr
contains the information to transform the
arguments.
source
argument to the
Format strings for the scanning functions are of the following form.
"source_spec > target_specs_and_literals"
where
target_specs_and_literals
source_spec
is a format specifier that describes the nature of the source parameter and
is a sequence of format specifiers and literal characters that
indicate how to divide and reformat the source argument into the desired target. Examples of format strings for the scanning functions are:
"%s >
%i" "%s > %20f[w10x]"
The character > is a visual reminder of the direction of the data transformation, and also separates the single source format specifier from the (possibly multiple) target format specifiers and literals. The source format specifier can be omitted, in which case a %s string format is assumed. If the source format specifier is omitted, the > character can be omitted also, or retained for clarity.
Notice that the source format specifier is located to the left of the > symbol, just as the source parameter is located to the left of the format string. Likewise, the target format specifiers are located to the right of the > symbol, just as the target parameters are located to the right of the format string.
Format specifiers describe the inputs and outputs of data transformations. Each format specifier is of the following form.
% [ rep ] formatcode [[ modifiers ]]
The character % introduces all format specifiers. repeats with respect to the arguments. nature of the data items being formatted.
formatcode
modifiers
rep
indicates how many times the format
is a code character which indicates the
is an optional bracket enclosed sequence
of codes which further describe the data format. The following are examples of format specifiers.
%s[t59] %100i[z] %f
Note:
© National Instruments Corporation 2-41 LabWindows/CVI Standard Libraries
rep
is not allowed when
formatcode
is s or l (string).
Formatting and I/O Library Chapter 2
formatcode is specified with one of the following codes:
s string. As a source or target specifier this indicates that the corresponding parameter is a
character string. As a source specifier the number of bytes of the source parameter that are consumed depends on the target specifier. If the target specifier is %s, bytes are consumed until a termination character is encountered (see the t modifier for strings for more information on termination characters). If the target specifier is one of the numeric formats, bytes are consumed as long as they correspond to the pattern for the particular numeric item being converted. Leading spaces and tabs are skipped unless the y modifier is used.
Note: When a target string is filled in, an ASCII NUL is always placed in the string
after the last byte.
l string. This is allowed only as a source specifier. It is the same as the %s specifier,
except that bytes from the source argument are to be consumed only until a linefeed is encountered. Also, when modified with c as in %l[c], a comma is used as the target string terminator in place of white space characters.
i integer. As a source or target specifier this indicates that the corresponding parameter is
an integer or, if rep is present, an integer array. As a source specifier in conversions to string formats, the integer is converted into digits of the specified radix (default is decimal). As a target specifier in conversions from string format, bytes of the source parameter are consumed as long as they match the pattern of integer ASCII numbers in the appropriate radix, or until the end of the string is encountered. The scanned characters are converted to integer values and placed into the corresponding target parameter, which is an integer or integer array passed by reference. If the format is repeated, the operation is repeated the appropriate number of times with successive elements of the integer array parameter.
The pattern for integer ASCII numbers depends on the radix of the number, and consists of an optional sign (+ or -), followed by a series of one or more digits in the appropriate radix. The decimal digits are 01234 56789. The octal digits are 01234567. The hexadecimal digits are 0123456789ABCDEFabcdef.
x integer (hexadecimal). This specifier indicates a %i format with hexadecimal radix. o integer (octal). This specifier indicates a %i format with octal radix. d integer (decimal). This specifier indicates a %i format with decimal radix. Since
decimal is the default radix for integers, %d is equivalent to %i, and is included for compatibility with the C scanf family of functions.
LabWindows/CVI Standard Libraries 2-42 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
f real number. As a source or target specifier, this indicates that the corresponding
parameter is a real number, or if rep is present, a real array. As a source specifier in conversions to string formats, the floating-point value is converted into ASCII form. As a target specifier in conversions from string format, bytes of the source parameter are consumed as long as they match the pattern of floating-point ASCII numbers, or until the end of the string is encountered. The scanned characters are converted to a floating-point value and placed into the corresponding floating-point or floating-point array target parameter. If the format is repeated, the operation is repeated the appropriate number of times with successive elements of the array parameter. The pattern for floating-point ASCII numbers is an optional sign (+ or -), a series of one or more decimal digits possibly containing a decimal point, and an optional exponent consisting of an E or e followed by an optionally signed decimal integer value.
c character. As a source specifier, this indicates that the source parameter is an integer with
one significant byte or, if rep is present, an array of 1-byte integers. As a target specifier this indicates that a byte of the source parameter is to be consumed, and the scanned character placed directly into the corresponding target parameter, which is an integer passed by reference. If the format is repeated, this operation is repeated the appropriate number of times and the results stored into successive elements of the integer array.

Scanning Modifiers

modifiers are optional codes used to describe the nature of the source or target data. If you use them, you must enclose the modifiers in square brackets and place them immediately after the format code they modify. If one format specifier requires more than one modifier, enclose all modifiers in the same set of brackets. There is a different set of modifiers for each possible format specifier.

Scanning Integer Modifiers (%i, %d, %x, %o, %c)

bn Specify Length. The b integer modifier specifies the length of the integer argument,
or the length of an individual integer array element, in bytes. The default length is 4 B; therefore, simple 4 B integers do not need this modifier. The modifier b2 represents short integers. The modifier b1 represents single-byte integers.
in Specify Array Offset. Use the i integer modifier to specify an offset within an
integer array argument. It indicates the location within the array where processing is to begin. n is the zero-based index of the first element to process. Thus, %10d[i2] applied to a source integer array reads the 10 integer values from the third through the twelfth elements of the array. The i modifier is valid only if rep is present. If the
i modifier is used with the z modifier, then n is in terms of bytes.
z Treat String as Integer Array. The z integer modifier indicates that the data type of
the corresponding argument is a string. Nevertheless, the data in the string is treated as an integer array. The z modifier is valid only if rep is present.
© National Instruments Corporation 2-43 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
rn Specify Radix. The r integer modifier specifies the radix of the integer argument,
which is important if the integer is converted from a string format. Legal radixes are 8 (octal), 10 (decimal, the default), 16 (hexadecimal), and 256 (a special radix representing single 8-bit ASCII characters).
wn Specify String Size. The w integer modifier specifies the exact number of bytes
occupied by a string representation of the integer argument, in the event that the integer is converted from a string format. You can enter any non-negative value here. If n is less than the number of digits required to represent the integer, an asterisk (*) will be inserted into the string to signify an overflow. The default for n is zero, which indicates that the integer can occupy whatever room is necessary.
s Specify as Two’s Complement. The s integer modifier indicates that the integer
argument is to be considered a signed two's complement number. This is the default interpretation of integers, so the s modifier is not required.
u Specify as Non-negative. The u integer modifier indicates that the integer is to be
considered a non-negative integer.
x Discard Terminator. The x integer causes the character that terminated the numeric
data to be discarded. In this way, terminator characters can be skipped when reading lists of numeric input. Thus, %3i[x] reads three integer numbers, disregarding the terminator character which appears after each one. You can use this specifier to scan the string 3, 7, -32.
d Discard Data. When applied to a target specifier, the d integer modifier indicates
that there is no target argument to correspond to the target specifier. The data that otherwise is placed in the target argument is discarded instead. The count returned by the Scan/ScanFile/ScanIn functions will include the target specifier even if the
d modifier is used.
onnnn Specify Byte Ordering. The o integer modifier is used to describe the byte ordering
of raw data so that LabWindows/CVI can map it to the byte order appropriate for the Intel (PC) or Motorola (SPARCstation) architecture. The number of n's must be equal to the byte size of the integer argument as specified by the bn modifier, which must precede the o modifier. In the case of a four-byte integer, o0123 indicates that the bytes are in ascending order of precedence (Intel style), and o3210 indicates that the bytes are in descending order of precedence (Motorola style).
In a Scan function, the buffer containing the raw instrument data should have the o modifier describing the byte ordering. The buffer without the o modifier is guaranteed to be in the mode of the host processor. LabWindows/CVI will reverse the byte ordering of the buffer without the o modifier depending on which architecture the program is running.
For example, if your GPIB instrument sends two-byte binary data in Intel byte order, your code should appear as follows.
LabWindows/CVI Standard Libraries 2-44 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
short int instr_buf[100]; short int prog_buf[100]; status = ibrd (ud, instr_buf, 200); Scan (instr_buf, "%100d[b2o01]>%100d", prog_buf);
If, instead, your GPIB instrument sends two-byte binary data in Motorola byte order,
Scan
the
Scan (instr_buf, "%100d[b2o10]>%100d", prog_buf);
function should appear as follows.
In either case, the o modifier is used only on the buffer containing the raw data from the instrument (
prog_buf
(
instr_buf
). LabWindows/CVI will ensure that the program buffer
) is in the proper byte order for the host processor.
Note: When using both the bn and on modifiers on an integer specifier, the bn modifier
must be first.

Scanning Floating-Point Modifiers (%f)

bn
in
z
wn
Specify Length. The b floating-point modifier specifies the length of the floating-point argument, or the length of an individual array element, in bytes. The default length is 8 B; therefore, double-precision values do not need this modifier. Single-precision floating-point values are indicated by b4. 8 and 4 are the only valid values for n.
Specify Array Offset. You can use the i floating-point modifier to specify an offset within a floating-point array argument. It indicates the location within the array where processing is to begin. n is the zero-based index of the first element to process. Thus,
%10f[i2]
applied to a source floating-point array reads the 10 floating-point values from the third through the twelfth elements of the array. The i modifier is valid only if
rep
is present. If you use the i modifier with the z modifier, then n is
in terms of bytes. Treat String as Floating Point. The z floating-point modifier indicates that the data
type of the corresponding argument is a string. Nevertheless, the data in the string is treated as a floating-point array. The z modifier is valid only if
rep
is present.
Specify String Size. The w floating-point modifier specifies the exact number of bytes occupied by a string representation of the floating-point argument, in the event that the value is converted from a string format. You can enter any non-negative value here. If n is less than the number of digits required to represent the floating-point number, an asterisk (*) will be inserted into the string to signify an overflow. The default for n is zero, which indicates that the value can occupy whatever space is necessary.
pn
Specify Precision. The p floating-point modifier specifies the number of digits to the right of the decimal point in a string representation of the floating-point number. Significant digits may be lost in attempting to conform to the precision specification.
© National Instruments Corporation 2-45 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
If the pn modifier is omitted, a default of p6 is used. The p modifier is valid for sources only.
en Specify as Scientific Notation. The e floating-point modifier indicates that the
string representation of the floating-point value is in scientific notation. If omitted, non-scientific notation is used. n is optional and specifies the number of digits to use in the exponent. For example, %f[e2] causes 10.0 to be formatted as 1.0e+01. If
n
is omitted, a default of three is used. The e modifier is valid for sources only.
f Specify as Floating Point. The f floating-point modifier indicates that the string
representation of the floating-point value is in non-scientific notation. This is the default even when the f modifier is not present.
x Discard Terminator. The x floating-point modifier causes the character that
terminated the numeric data to be discarded. In this way, terminator characters can be skipped when reading lists of numeric input. Thus, %3f[x] reads three floating­point numbers, disregarding the terminator character which appears after each one; this specifier could then be used to scan the string 3.5, 7.6, -32.4.
d Discard Data. When applied to a target specifier, the d modifier indicates there is no
target argument to correspond to the target specifier. The data that otherwise is placed in the target argument is discarded instead. The count returned by the
Scan/ScanFile/ScanIn functions will include the target specifier even if the d modifier is used.

Scanning String Modifiers (%s)

in Specify Array Offset. The i string modifier specifies an offset within a string. It
indicates the location within the string where processing is to begin. n is the zero­based index of the first byte to process. Thus, %s[i2] applied to a target string begins placing data in the third byte of the string.
a Append. When applied to a target format specifier, the a string modifier specifies
that all formatted data be appended to the target string, beginning at the first occurrence of an ASCII NUL in the target string.
wn Specify String Size. When modifying a source format specifier, the w string modifier
specifies the maximum number of bytes from the source string to be used for filling the target arguments. You can enter any non-negative value here, the default being zero, which indicates that the entire string can be used. (For ScanFile and ScanIn, the entire source string is consumed even if the w modifier restricts the number of bytes used to fill in the target arguments.)
When modifying a target format specifier, the w modifier specifies the exact number of bytes to store in the string, excluding the terminating ASCII NUL. If n is zero or omitted, as many bytes are stored as are called for by the sources. When n is greater
LabWindows/CVI Standard Libraries 2-46 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
than the number of bytes available from the source, the remaining bytes are filled with ASCII NULs if the q modifier is used or blanks if the q modifier is not present.
When the w modifier is used in conjunction with the a modifier, n indicates the number of bytes to append to the string excluding the terminating ASCII NUL.
If wn modifies a target string and n is larger than the number of bytes in the target argument, the target argument is overwritten in compiled C.
q Append NULs. When applied to a target string in conjunction with the w string
modifier, the q string modifier specifies that unfilled bytes at the end of the target string be set to ASCII NULs instead of blanks.
y Append with Spacing. When the source is a string and the y modifier is applied to a
target string format specifier, the target string is filled with bytes from the source string without skipping leading spaces or tabs.
tn Terminate on Character. When applied to a source string, the t modifier specifies
that the source string is terminated on the first occurrence of the character n, where
n
is the ASCII value of the character. Thus, %s[t44] causes reading of the source string to stop on an ASCII comma. More than one t modifier can occur in the same specifier, in which case the string terminates when any of the terminators occur. If no t modifier is present, reading of the source string stops on an ASCII NUL.
When applied to a target string that is being filled from a source string, the t modifier specifies that filling of the target is terminated on the first occurrence of the character
n
, where n is the ASCII value of the character. Thus, %s[t59] causes reading of the source string to stop on an ASCII semicolon. More than one t modifier can occur in the same specifier, in which case filling of the target terminates when any of the terminators occur. If no t modifier is present, filling of the target stops on any whitespace character.
t- Terminate when Full. This is similar to tn, except that it specifies that there are no
terminating characters. When applied to a source string, t- specifies that reading of the source string terminates when all of the targets are full or when the number of bytes specified with the w modifier have been read. When applied to a target string, t- specifies that filling of the target string terminates when the source is exhausted or when the number of bytes specified with the w modifier have been placed into the target.
t# Terminate on Number. This is equivalent to repeating the t modifier with the
ASCII values of the characters +, -, and 0 through 9. When applied to a source (target), it specifies that reading of the source string (filling of the target string) be terminated upon occurrence of a numeric expression. Using %s>%s[t#]%d with the source string ab567, ab is placed in the first target and the integer 567 is placed in the second target.
© National Instruments Corporation 2-47 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
x Discard Terminator. When applied to a target string, the x modifier specifies that
the terminating character be discarded before the next target is filled in. Using %s>%s[xt59]%s[xt59] with the source string "abc;XYZ;", "abc" is placed in the first target and "XYZ" is placed in the second target.
d Discard Data. When applied to a target specifier, the d modifier indicates that there
is no target argument to correspond to the target specifier. The data that otherwise is placed in the target argument is discarded instead. The count returned by the
Scan/ScanFile/ScanIn functions will include the target specifier even if the d modifier is used.

Scan, ScanFile, ScanIn—Asterisks (*) Instead of Constants in Format Specifiers

Often, a format specifier requires one or more integer values. The format specifier for an integer array, for example, requires the number of elements (rep). You can use constants for these integer values in format specifiers. Alternatively, you can specify an integer value using an argument in the argument list. When you use this method, substitute an asterisk (*) for the constant in the format specifier. Use the asterisk in the following format specifier elements.
rep For integer or floating-point arrays. in For integer or floating-point arrays, or strings. wn For any format specifier. pn For floating-point specifiers only. en For floating-point specifiers only. rn For integer specifiers only.
When you use one or more asterisks instead of constants in a source specifier, the arguments corresponding to the asterisks must appear after the format string in the same order as their corresponding asterisks appear in the format specifier.
When you use one or more asterisks instead of constants in a target specifier, the arguments corresponding to the asterisks must precede the target argument and must be in the same order as their corresponding asterisks in the format specifier.

Scan, ScanFile, ScanIn—Literals in the Format String

Literal characters appearing in a scanning function format string indicate that the literal characters are expected in the source parameter. They are not stored into any target parameter, but are skipped over when encountered. If a literal character specified in the format string fails to appear in the source in the expected position, the scanning function immediately returns.
LabWindows/CVI Standard Libraries 2-48 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Some formats may have been correctly detected in the input, and the corresponding target parameters will have been filled in. Formats situated after the literal which did not appear, however, will not have been executed.
The function return value can be used to determine exactly how many target parameters were actually fulfilled by the input. You can use the function NumFmtdBytes to determine the number of bytes consumed from the source parameter.
Because the left side of the > symbol must be a single format specifier, literal characters, if present, must be on the right side of the symbol. Literals on the left side, or more than one format specifier on the left side, result in a -1 error, indicating a faulty format string. The function GetFmtErrNdx can then be used to determine exactly where in the format string the error lies.
The characters %, [, ], <, and > have special meaning in the format strings. To specify that these characters be taken literally, they should be preceded by %.

Formatting and I/O Library Programming Examples

This section contains examples of program code that use the Formatting and I/O Library functions. The formatting and scanning functions are the basis of most of the examples.
The Fmt/FmtFile/FmtOut examples are logically organized as shown:
Integer to String Long Integer to String Real to String in Floating-Point Notation Real to String in Scientific Notation Integer and Real to String with Literals Two Integers to ASCII File with Error Checking Real Array to ASCII File in Columns and with Comma Separators Integer Array to Binary File, Assuming a Fixed Number of Elements Real Array to Binary File, Assuming a Fixed Number of Elements Real Array to Binary File, Assuming a Variable Number of Elements A Variable Portion of a Real Array to a Binary File Concatenating Two Strings Appending to a String Creating an Array of File Names Writing a Line Containing an Integer with Literals to the Standard Output Writing to the Standard Output without a Linefeed/Carriage Return
The Scan/ScanFile/ScanIn examples are logically organized as shown:
String to Integer String to Long Integer String to Real
© National Instruments Corporation 2-49 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
String to Integer and Real String to String String to Integer and String String to Real, Skipping over Non-Numeric Characters in the String String to Real, after Finding a Semicolon in the String String to Real, after Finding a Substring in the String String with Comma-Separated ASCII Numbers to Real Array Scanning Strings That Are Not NUL-Terminated Integer Array to Real Array Integer Array to Real Array with Byte Swapping Integer Array Containing 1-Byte Integers to Real Array String Containing Binary Integers to Integer Array String Containing an IEEE-Format Real Number to a Real Variable ASCII File to Two Integers with Error Checking ASCII File with Comma-Separated Numbers to Real Array, with Number of Elements
at Beginning of File
Binary File to Integer Array, Assuming a Fixed Number of Elements Binary File to Real Array, Assuming a Fixed Number of Elements Binary File to Real Array, with Number of Elements at Beginning of File Reading an Integer from the Standard Input Reading a String from the Standard Input Reading a Line from the Standard Input

Fmt/FmtFile/FmtOut Examples in C

This section contains examples of program code that use the Fmt, FmtFile, and FmtOut functions from the Formatting and I/O Library. To eliminate redundancy, error checking on I/O operations has been omitted from all of the examples in this section except the Two Integers to ASCII File with Error Checking example.

Integer to String

char buf[10]; int a; a = 16; Fmt (buf, "%s<%i", a); /* result: "16" */ a = 16; Fmt (buf, "%s<%x", a); /* result: "10" */ a = 16; Fmt (buf, "%s<%o", a); /* result: "20" */ a = -1; Fmt (buf, "%s<%i", a); /* result: "-1" */ a = -1; Fmt (buf, "%s<%i[u]", a); /* result: "4294967295" */ a = 1234; Fmt (buf, "%s<%i[w6]", a); /* result: " 1234" */ a = 1234;
LabWindows/CVI Standard Libraries 2-50 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
Fmt (buf, "%s<%i[w6p0]", a); /* result: "001234" */ a = 1234; Fmt (buf, "%s<%i[w2]", a); /* result: "*4" */
Remarks
The results shown are the contents of
buf
after each call to
Fmt
. The last call demonstrates
what occurs when the width specified by the w modifier is too small.

Long Integer to String

char buf[20]; long a; a = 123456; Fmt (buf, "%s<%i[b4]", a); /* result: "123456" */ a = 123456; Fmt (buf, "%s<%x[b4]", a); /* result: "1e240" */ a = 123456; Fmt (buf, "%s<%o[b4]", a); /* result: "361100" */ a = -1; Fmt (buf, "%s<%i[b4]", a); /* result: "-1" */ a = -1; Fmt (buf, "%s<%i[b4u]", a); /* result: "4294967295" */ a = 123456; Fmt (buf, "%s<%i[b4w8]", a); /* result: " 123456" */ a = 123456; Fmt (buf, "%s<%i[b4w8p0]", a); /* result: "00123456" */ a = 123456; Fmt (buf, "%s<%i[b4w4]", a); /* result: "*456" */
Remarks
The results shown are the contents of
buf
after each call to
Fmt
. The last call demonstrates
what occurs when the width specified by the w modifier is too small.

Real to String in Floating-Point Notation

char buf[30] double x; x = 12.3456789; Fmt (buf, "%s<%f", x); /* result: "12.345679" */ x = 12.3456789; Fmt (buf, "%s<%f[p2]", x); /* result: "12.35" */ x = 12.3456789; Fmt (buf, "%s<%f[p10]", x); /* result: "12.3456789000" */ x = 12.345; Fmt (buf, "%s<%f", x); /* result: "12.345" */ x = 12.345;
© National Instruments Corporation 2-51 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Fmt (buf, "%s<%f[p0]", x); /* result: "12." */ x = 12.345; Fmt (buf, "%s<%f[p6]", x); /* result: "12.345000" */ x = -12.345; Fmt (buf, "%s<%f[w12]", x); /* result: "-12.345" */ x = -12.3456789; Fmt (buf, "%s<%f[w6]", x); /* result: "-12.3*" */ x = 0.00000012; Fmt (buf, "%s<%f[p8]", x); /* result: "0.00000012" */ x = 0.00000012; Fmt (buf, "%s<%f", x); /* result: "1.2e-007" */ x = 4.5e050; Fmt (buf, "%s<%f", x); /* result: "4.5e050" */
Remarks
The results shown are the contents of
buf
after each call to
Fmt
. The last two calls demonstrate
that very large and very small values are sometimes forced into scientific notation even when the
e
modifier is absent.

Real to String in Scientific Notation

char buf[20]; double x; x = 12.3456789; Fmt (buf, "%s<%f[e]", x); /* result: "1.234568e+001" */ x = 12.3456789; Fmt (buf, "%s<%f[ep2]", x); /* result: "1.23e+001" */ x = 12.3456789; Fmt (buf, "%s<%f[e2p2]", x); /* result: "1.23e+01" */ x = 12.345; Fmt (buf, "%s<%f[e]", x); /* result: "1.234500e+001" */ x = 12.345; Fmt (buf, "%s<%f[ep2w12]", x); /* result: " 1.23e+001" */ x = 12.345; Fmt (buf, "%s<%f[ep2w6]", x); /* result: "1.23e*" */
Remarks
The results shown are the contents of
buf
after each call to
Fmt
. The last call demonstrates
what occurs when the width specified by the w modifier is too small.
LabWindows/CVI Standard Libraries 2-52 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

Integer and Real to String with Literals

char buf[20]; int f, r; double v; f = 4; r = 3; v = 1.2; Fmt (buf, "%s<F%iR%i; V%f;", f, r, v);
Remarks
After the
Fmt
call,
buf
contains
"F4R3; V1.2;"
.

Two Integers to ASCII File with Error Checking

int a, b, n, file_handle; a = 12; b = 456; file_handle = OpenFile ("FILE.DAT", 2, 0, 1); if (file_handle < 0) {
FmtOut ("Error opening file\n");
exit (1); } n = FmtFile (file_handle, "%s<%i %i", a, b); if (n != 2) {
FmtOut ("Error writing file\n");
exit (1); } CloseFile (file_handle);
Remarks
OpenFile
opens the file
FILE.DAT
as an ASCII file for writing only. If the function succeeds, it returns a file handle with a positive integer value. representation of two integer values to the file. If
FmtFile
succeeds, it returns 2 (because there
are two source specifiers in the format string).
FmtFile
writes the ASCII

Real Array to ASCII File in Columns and with Comma Separators

double x[100]; int file_handle, i; file_handle = OpenFile ("FILE.DAT", 2, 0, 1); for (i=0; i < 100; i++) {
FmtFile (file_handle, "%s<%f[w15],", x[i]);
© National Instruments Corporation 2-53 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
if ((i % 5) == 4)
WriteFile (file_handle, "\n", 1); } CloseFile (file_handle);
Remarks
FmtFile
The
call writes the ASCII representation of a real array element to the file, followed
by a comma. The w modifier specifies that the number be right-justified in a 15-character field.
WriteFile
The
call writes a linefeed to the file after every fifth call to
FmtFile
. Because the file is opened in ASCII mode, the linefeed is automatically written as a linefeed/carriage return combination.
Note: If the format string is "
%s[w15]<%f,
", the number and the comma are left-justified
together in a 15-character field.

Integer Array to Binary File, Assuming a Fixed Number of Elements

int readings[100]; int file_handle, nbytes; file_handle = OpenFile ("FILE.DAT", 2, 0, 0); FmtFile (file_handle, "%100i<%100i", readings); nbytes = NumFmtdBytes (); CloseFile (file_handle)
Remarks
FmtFile
The form. If the
call writes all 100 elements of the integer array
FmtFile
call is successful,
nbytes
= 200 (100 integers, 2 bytes per integer).
readings

Real Array to Binary File, Assuming a Fixed Number of Elements

to a file in binary
double waveform[100]; int file_handle, nbytes; file_handle = OpenFile ("FILE.DAT", 2, 0, 0); FmtFile (file_handle, "%100f<%100f", waveform); nbytes = NumFmtdBytes (); CloseFile (file_handle);
Remarks
FmtFile
The
FmtFile
If the
LabWindows/CVI Standard Libraries 2-54 © National Instruments Corporation
call writes all 100 elements of the real array
call is successful,
nbytes
= 800 (100 integers, 8 bytes per real number).
waveform
to a file in binary form.
Chapter 2 Formatting and I/O Library

Real Array to Binary File, Assuming a Variable Number of Elements

void StoreArray (double x[], int count, char filename[]) {
int file_handle; file_handle = OpenFile (filename, 2, 0, 0); FmtFile (file_handle, "%*f<%*f", count, count, x); CloseFile (file_handle);
}
Remarks
This example shows how a function can be used to write an array of real numbers to a binary file. The function's parameters are a real array, the number of elements to be written, and the filename.
FmtFile
The
call writes the first asterisks (*) in the format string are matched to format string is equivalent to
count
%100f<100f
elements of x to a file in binary form. The two
count
. For instance, if
count
is 100, then the
.

A Variable Portion of a Real Array to a Binary File

void StoreSubArray (double x[], int start, int count, char filename[]) {
int file_handle; file_handle = OpenFile (filename, 2, 0, 0); FmtFile (file_handle, "%*f<%*f[i*]", count, count, start, x); CloseFile (file_handle)
}
Remarks
This example is an extension of the previous example. The function also writes a variable number of elements of a real array to a file. Instead of beginning at the first element of the array, a starting index is passed to the function.
FmtFile
The
call writes form. The first two asterisks (*) in the format string are matched to is matched to equivalent to
start
%100f<100f[i30]
the real array, the array elements from
count
elements of x, starting from
. For instance, if
. Because the i modifier specifies a zero-based index into
count
x[30]
is 100 and
through
x[129]
x[start]
count
start
is 30, then the format string is
are written to the file.
, to a file in binary
. The third asterisk
© National Instruments Corporation 2-55 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2

Concatenating Two Strings

char buf[30]; int wave_type, signal_output; char *wave_str, *signal_str; int nbytes; wave_type = 1; signal_output = 0; switch (wave_type) {
case 0:
wave_str = "SINE;" break;
case 1:
wave_str = "SQUARE;" break;
case 2:
wave_str = "TRIANGLE;"
break; } switch (signal_output) {
case 0:
signal_str = "OUTPUT OFF;"
break;
case 1:
signal_str = "OUTPUT ON;"
break; } Fmt (buf, "%s<%s%s", wave_str, signal_str); nbytes = NumFmtdBytes ();
Remarks
The two
signal_str buf
switch
constructs assign constant strings to the string variables
. The
. After the call,
Fmt
buf
call concatenates the contents of
contains
"SQUARE;OUTPUT OFF;". NumFmtdBytes
the number of bytes in the concatenated string.

Appending to a String

char buf[30]; int wave_type, signal_output; int nbytes; switch (wave_type) {
case 0:
Fmt (buf, "%s<SINE;");
break;
case 1:
Fmt (buf, "%s<SQUARE;");
break;
wave_str
wave_str
signal_str
and
and
into
returns
LabWindows/CVI Standard Libraries 2-56 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
case 2:
Fmt (buf, "%s<TRIANGLE;");
break; } switch (signal_output) {
case 0:
Fmt (buf, "%s[a]<OUTPUT OFF;");
break;
case 1:
Fmt (buf, "%s[a]<OUTPUT ON;");
break; } nbytes = StringLength (buf);
Remarks
This example shows how to append characters to a string without writing over the existing contents of the string. The first second call,
switch
buf
construct appends one of two strings to the string already in
contains
"SQUARE;OUTPUT OFF;"
switch
construct writes one of three strings into
. Notice that the a modifier applies to the
buf
. After the
buf
. The
target specifier.
StringLength StringLength
returns the number of bytes in the resulting string. In this case, is used instead of
NumFmtdBytes
, because
NumFmtdBytes
would return
only the number of bytes appended.

Creating an Array of File Names

char *fname_array[4]; int i; fname_array[0] = " "; /* 13 spaces */ fname_array[1] = " "; /* 13 spaces */ fname_array[2] = " "; /* 13 spaces */ fname_array[3] = " "; /* 13 spaces */ for (i=0; i < 4; i++)
Fmt (fname_array[i], "%s<FILE%i[w4p0].DAT", i);
Remarks
To allocate the space for each filename in the array, a separate constant string must be assigned to each array element. Then
FILE0000.DAT, FILE0001.DAT, FILE0002.DAT
Fmt
is used to format each file name. The resulting file names are
FILE0003.DAT
, and
.
© National Instruments Corporation 2-57 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2

Writing a Line Containing an Integer with Literals to the Standard Output

int a, b; a = 12; b = 34; FmtOut ("%s<A = %i\n", a); FmtOut ("%s<B = %i\n", b);
Remarks
In this example, the output is as follows:
A = 12
B = 34

Writing to the Standard Output without a Linefeed/Carriage Return

char *s; int b; double c; a = "One "; FmtOut ("%s<%s", a); b = 2; FmtOut ("%s<%i", b); c = 3.4; FmtOut ("%s<%f", c);
Remarks
This example demonstrates how to write to the Standard Output without a linefeed/carriage return by omitting the
One 2 3.4
'\n
' from the format string. The output in this example is as follows.
The following code produces the same output:
a = "One"; b = 2; c = 3.4; FmtOut ("%s<%s %i %f", a, b, c);
LabWindows/CVI Standard Libraries 2-58 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

Scan/ScanFile/ScanIn Examples in C

This section contains examples of program code that use the Scan, ScanFile, and ScanIn functions from the Formatting and I/O Library. To eliminate redundancy, the examples include no error checking on I/O operations in this section except for the ASCII File to Two Integers with Error Checking example.

String to Integer

char *s; int a, n; s = "32"; n = Scan (s, "%s>%i", &a); /* result: a = 32, n = 1 */ s = "-32"; n = Scan (s, "%s>%i", &a); /* result: a = -32, n = 1 */ s = " +32"; n = Scan (s, "%s>%i", &a); /* result: a = 32, n = 1 */ s = "x32"; n = Scan (s, "%s>%i", &a); /* result: a = ??, n = 0 */
Remarks
When locating an integer in a string, Scan skips over white space characters such as spaces, tabs, linefeeds, and carriage returns. If a non-numeric character other than a white space character, +, or - is found before the first numeric character, the Scan call fails. Thus, Scan fails on the x in x32; it leaves the value in a unmodified and returns zero, indicating that no target specifiers were satisfied.
s = "032"; n = Scan (s, "%s>%i", &a); /* result: a = 32, n = 1 */ s = "32a"; n = Scan (s, "%s>%i", &a); /* result: a = 32, n = 1 */ s = "32"; n = Scan (s, "%s>%o", &a); /* result: a = 26, n = 1 */ s = "32"; n = Scan (s, "%s>%x", &a); /* result: a = 50, n = 1 */
Remarks
When the %i specifier is used, numeric characters are interpreted as decimal, even when they might appear to be octal (as in 032) or hexadecimal (as in 32a). When the %o specifier is used, the numeric characters (01234567) are always interpreted as octal. When the %x specifier is used, the numeric characters (0123456789abcdef) are always interpreted as hexadecimal.
s = "32x1"; n = Scan (s, "%s>%i", &a); /* result: a = 32, n = 1 */
© National Instruments Corporation 2-59 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Scan considers the occurrence of a non-numeric character (such as the x in 32x1) to mark the end of the integer.
s = "32567"; n = Scan (s, "%s>%i[w3]", &a); /* result: a = 325, n = 1 */
The w3 modifier specifies that only the first 3 bytes of the string are scanned.

String to Long Integer

char *s; long a; int n; s = "99999"; n = Scan (s, "%s>%i[b4]", &a); /* result: a = 99999, n = 1 */ s = "303237"; n = Scan (s, "%s>%o[b4]", &a); /* result: a = 99999, n = 1 */ s = "ffff"; n = Scan (s, "%s>%x[b4]", &a); /* result: a = 65535, n = 1 */
Remarks
Scan extracts long integers from strings in the same way it extracts integers. The only differences are that the b4 modifier must be used and the target argument must be a long integer. See the String to Integer example earlier in this section for more details on using Scan to extract integers and long integers from strings.

String to Real

char *s; double x; int n; s = "12.3"; n = Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */ s = "-1.23e+1"; n = Scan (s, "%s>%f", &x); /* result: x = -1.23, n = 1 */ s = "1.23e-1"; n = Scan (s, "%s>%f", &x); /* result: x = 0.123, n = 1 */
Remarks
When locating a real number in a string, Scan accepts either floating-point notation or scientific notation.
s = " 12.3"; n = Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */ s = "p12.3"; n = Scan (s, "%s>%f", &x); /* result: x = ????, n = 0 */
LabWindows/CVI Standard Libraries 2-60 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
When locating a real number in a string, Scan skips over white space characters. If a non­numeric character other than a white space character, +, or - is found before the first numeric character, the Scan call fails. Thus, Scan fails on the p in p12.3; it leaves the value in x unmodified and returns zero, indicating that no target specifiers were satisfied.
s = "12.3m"; n = Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */ s = "12.3.4"; n = Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */ s = "1.23e"; n = Scan (s, "%s>%f", &x); /* result: x = ????, n = 0 */
Scan considers the occurrence of a non-numeric character (such as the m in 12.3m) to mark the
end of the real number. A second decimal point also marks the end of the number. However,
Scan fails on "1.23e" because the value of the exponent is missing.
s = "1.2345"; n = Scan (s, "%s>%f[w4]", &x);/* result: x = 1.23, n = 1 */
The w4 modifier specifies that only the first 4 bytes of the string are scanned.

String to Integer and Real

char *s; int a, n; double x; s = "32 1.23"; n = Scan (s, "%s>%i%f", &a, &x);
/* result: a = 32, x = 1.23, n = 2 */
s = "32, 1.23"; n = Scan (s, "%s>%i[x]%f", &a, &x);
/* result: a = 32, x = 1.23, n = 2 */
s = "32, 1.23"; n = Scan (s, "%s>%i%f", &a, &x);
/* result: a = 32, x = ????, n = 1 */
Remarks
After each of the first two calls to Scan, a = 32, x = 1.23, and n = 2 (indicating that two target specifiers were satisfied). In the second call, the x modifier is used to discard the separating comma.
In the third call, there is a comma separator after the integer, but the x modifier is absent. Consequently, Scan fails when attempting to find the real number. x remains unmodified, and n = 1 (indicating that only one target specifier was satisfied).
© National Instruments Corporation 2-61 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2

String to String

char *s; char buf[10]; int n; s = " abc "; n = Scan (s, "%s>%s", buf); /* result: buf = "abc" */ s = " abc "; n = Scan (s, "%s>%s[y]", buf); /* result: buf = " abc" */
Remarks
When extracting a substring from a string,
Scan
skips leading spaces and tabs unless the
y
modifier is present.
s = "a b c; d"; n = Scan (s, "%s>%s", buf); /* result: buf = "a" */ s = "a b c; d"; n = Scan (s, "%s>%s[t59]", buf); /* result: buf = "a b c" */
When
Scan
extracts a substring from a string and the t modifier is not present, the substring is considered to be terminated by a white space character. To include embedded white space in the target string, use the t modifier to change the target string termination character. In the second call to
Scan, [t59]
s = " abcdefghijklmnop"; n = Scan (s, "%s>%s[w9]", buf);
s = " abc"; n = Scan (s, "%s>%s[w9]", buf); /* result: buf = "abc "*/ s = " abc" n = Scan (s, "%s>%s[w9q]", buf); /* result: buf = "abc" */
changes the termination character to a semicolon (ASCII 59).
/* result: buf = "abcdefghi" */
Remarks
The w modifier can be used to prevent width specified does not include the ASCII NUL that
Scan
from writing beyond the end of a target string. The
Scan
places at the end of the target string. Therefore, the width specified should be at least one less than the width of the target character buffer.
When the w modifier is used and the string extracted is smaller than the width specified, the remaining bytes in the target string are blank-filled. However, if the q modifier is also used, ASCII NULs fill the remaining bytes.
LabWindows/CVI Standard Libraries 2-62 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

String to Integer and String

char *s; char buf[10]; int a, n; s = "32abc"; n = Scan (s, "%s>%i%s", &a, buf);
/* result: a = 32, buf = "abc", n = 2 */ s = "32abc"; n = Scan (s, "%s>%i %s", &a, buf);
/* result: a = 32, buf = ?????, n = 1 */
Remarks
After the first call to
Scan, a
= 32,
buf
"abc"
=
, and n = 2. Notice there are no spaces in the format string between the two target specifiers. In the second call, there is a space between and %s. Consequently, Because there is no space in s,
Scan
expects a space to occur in s immediately after the integer.
Scan
fails at that point. It leaves
buf
unmodified and returns 1
(indicating that only one target specifier is satisfied). Note: Do not put spaces between specifiers in
Scan, ScanFile
, or
ScanIn
format strings.

String to Real, Skipping over Non-Numeric Characters in the String

char *s; double x; int n; s = "VOLTS = 1.2"; n = Scan (s, "%s>%s[dt#]%f", &x); /* result: x = 1.2, n = 2 */ s = "VOLTS = 1.2"; n = Scan (s, "%s[i8]>%f", &x); /* result: x = 1.2, n = 1 */ s = "VOLTS = 1.2"; n = Scan (s, "%s>VOLTS = %f", &x); /* result: x = 1.2, n = 1 */
Remarks
%i
The three different format strings represent different methods for skipping over non-numeric characters. In the first call, the format string contains two target specifiers. In the first specifier
%s[dt#]
(
), the
t#
modifier instructs
Scan
to read bytes from s until a number is encountered. The d modifier indicates that the bytes must be discarded because there is no argument corresponding to the specifier. When the
Scan
call succeeds, it returns 2, indicating
that two target specifiers were satisfied, even though there is only one target argument. In the second call, the source specifier
%s[i8]
instructs
Scan
to ignore the first 8 bytes of s.
This method works only if the location of the number within s is always the same. In the third call, the format string contains the non-numeric characters literally. This method
works only if the non-numeric characters in s are always the same.
© National Instruments Corporation 2-63 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2

String to Real, After Finding a Semicolon in the String

char *s; double x; int n; s = "TIME 12:45:00; 7.34"; n = Scan (s, "%s>%s[xdt59]%f", &x);
/* result: x = 7.34, n = 2 */
Remarks
Some strings returned by programmable instruments contain headers that consist of numeric as well as non-numeric data and are terminated by a particular character, such as a semicolon. This example shows how such a header can be skipped.
The format string contains two target specifiers. In the first specifier ( modifier instructs
Scan
to read bytes from s until a number is encountered. The d modifier
%s[xdt#]
), the
t#
indicates that the bytes must be discarded because there is no argument corresponding to the specifier. The x modifier indicates that the semicolon should also be discarded.
When the
Scan
call succeeds, it returns 2, indicating that two target specifiers were satisfied,
even though there is only one target argument.

String to Real, After Finding a Substring in the String

char *s; double x; int index, n; s = "HEADER: R5 D6; DATA 3.71E+2"; index = FindPattern (s, 0, -1, "DATA", 0, 0) + 4; n = Scan (s, "%s[i*]>%f", index, &x);
/* result: x = 371.0, n = 1 */
Remarks
This example is similar to the previous one, except that portion of the string to be skipped is terminated by a substring ( Library function
FindPattern
added to the index so that it points to the first byte after
Scan
and matched with the asterisk (*) in the format string.
DATA
) rather than by a single character. The Formatting and I/O
is used to find the index where
DATA
DATA
begins in s. Four is
. The index is then passed to
In this example,
FindPattern
returns 15, and
asterisk in the format string in the
i19
The
indicates that the first 19 bytes of s should be ignored.
number from the remaining string,
Scan
call, the format string is interpreted as
3.71E+2
index
is 19. When
, and assigns it to x.
index
Scan
then extracts the real
Scan
is matched to the
returns 1, indicating
%s[i19]>%f
.
that one target specifier is satisfied.
LabWindows/CVI Standard Libraries 2-64 © National Instruments Corporation
Chapter 2 Formatting and I/O Library

String with Comma-Separated ASCII Numbers to Real Array

char *s; int n; double a[5]; /* 5 8-byte real numbers */ s = "12.3, 45, 6.5, -1.3E-2, 4"; n = Scan (s, "%s>%5f[x]", a);
/* result: a[0] = 12.3, a[1] = 45.0, a[2] = 6.5, */ /* a[3] = -0.013, a[4] = 4.0, n = 1 */
Remarks
The x modifier causes the comma separators to be discarded.
Scan
considers an array target to be satisfied when at least one element of the array is filled in. If the source string in this example were other elements would remain unmodified, and
12.3
, only the first element of a would be filled in, the
Scan
would return 1.

Scanning Strings That Are Not NUL-Terminated

int bd; double x; char s[20]; ibrd (bd, s, 15); Scan (s, "%s[w*]>%f", ibcnt, &x);
Remarks
All of the previous examples assume that s is a NUL-terminated string. However, when reading data from programmable instruments using the GPIB and RS-232 Library functions, the data transferred is not NUL-terminated. This example uses instrument. The global variable uses the value in
ibcnt
in conjunction with the w modifier to specify the width of the source
ibcnt
contains the actual number of bytes transferred.
ibrd
to read up to 15 B from a GPIB
Scan
string. For example, if
ibcnt
is 12, the format string is interpreted as
%s[w12]>%f
, causing
Scan
to
use only the first 12 bytes of s. The following example is an alternative method for handling strings that are not
NUL-terminated:
int bd; double x; char s[20]; ibrd (bd, s, 15); s[15] = 0; /* ASCII NUL is 0 */ Scan (s, "%s>%f", &x);
© National Instruments Corporation 2-65 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
This code shows how to insert an ASCII NUL at the end of the transferred bytes. After the assignment, s is NUL-terminated.

Integer Array to Real Array

int ivals[100]; double dvals[100]; Scan (ivals, "%100i>%100f", dvals);
Remarks
Each integer in ivals is converted to real number and then written into dvals.

Integer Array to Real Array with Byte Swapping

int ivals[100]; double dvals[100]; Scan (ivals, "%100i[o10]>%100f", dvals);
Remarks
Each integer in ivals is byte-swapped, converted to a real number, and written into dvals. Byte swapping is useful when a programmable instrument sends back 2-byte integers with the
high byte first, followed by the low byte. When this data is read into an integer array, the placement of the bytes is such that the high byte is interpreted as the low byte. The o10 modifier specifies that the bytes be interpreted in the opposite order.

Integer Array Containing 1-Byte Integers to Real Array

int ivals[50]; /* 100 1-byte integers */ double dvals[100]; /* 100 8-byte real numbers */ Scan (ivals, "%100i[b1]>%100f", dvals); Scan (ivals, "%100i[b1u]>%100f", dvals);
Remarks
Sometimes, each element in an integer array is used to store two 1-byte integers. This example shows how to unpack the 1-byte integers and store them in a real array. The b1 indicates that each binary integer is only one byte long.
LabWindows/CVI Standard Libraries 2-66 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
The first call to Scan treats the 1-byte integers as signed values (from -128 to +127). The second call includes a u in the format string. This causes Scan to treat the 1-byte integers as unsigned values (from 0 to 255).

String Containing Binary Integers to Integer Array

char s[200]; /* string containing 100 2-byte integers */ int ivals[100];/* 100 2-byte integers */ Scan (s, "%100i[z]>%100i", ivals); Scan (s, "%97i[zi6]>%97i", ivals);
Remarks
Sometimes data from a programmable instrument is read into a character buffer even though it contains binary data. This example shows how to treat a character buffer as an integer array. The format string in each Scan call specifies that the source (s) contains an array of 100 integers. The z modifier is used to indicate that the source is actually a character buffer.
In some cases, the integer data may not start at the beginning of the character buffer. For instance, the data in the buffer can begin with an ASCII header. In the second call to Scan, the i6 modifier is used to indicate that the first 6 bytes of s are to be ignored.
Note: When the i modifier is used in conjunction with a character buffer, the number
following the i specifies the number of bytes within the buffer to ignore. This is true even when the z modifier is also present. On the other hand, when the i modifier is used in conjunction with an array variable, the number following the i indicates the number of array elements to ignore.

String Containing an IEEE-Format Real Number to a Real Variable

char s[100]; double x; Scan (s, "%1f[z]>%f", &x); Scan (s, "%1f[zi5]>%f", &x);
Remarks
This example is similar to the previous example, except that s contains a single binary real number (in IEEE format), rather an array of binary integers. The format string in each Scan call indicates that the source (s) is to be treated as a 1-element array of real numbers. The z modifier indicates that the source is actually a character buffer. The repetition count of 1 in the format string is required; otherwise, the z modifier is not accepted.
© National Instruments Corporation 2-67 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
The first call to Scan assumes that the real number is at the beginning of s. The second call assumes that the real number starts at the sixth byte of s. The i5 modifier causes the first 5 bytes of s to be ignored.

ASCII File to Two Integers with Error Checking

int file_handle, n, a, b; file_handle = OpenFile ("FILE.DAT", 1, 2, 1); if (file_handle < 0) {
FmtOut ("Error opening file\n");
exit (1); } n = ScanFile (file_handle, "%s>%i%i", &a, &b); if (n != 2) {
FmtOut ("Error reading file\n");
exit (1); } CloseFile (file_handle);
Remarks
OpenFile opens the file FILE.DAT as an ASCII file for reading only. If OpenFile succeeds in opening the file, it returns a file handle with a positive integer value. ScanFile reads the ASCII representation of two integer values from the file. If ScanFile succeeds, it returns 2 (indicating that two target specifiers were satisfied).

ASCII File with Comma Separated Numbers to Real Array, with Number of Elements at Beginning of File

double values[1000]; int file_handle, count; file_handle = OpenFile ("FILE.DAT", 1, 2, 1); ScanFile (file_handle, "%s>%i", &count); if (count > 1000) {
FmtOut ("Count too large\n");
exit(1); } ScanFile (file_handle, "%s>%*f[x]", count, values); CloseFile (file_handle);
Remarks
The first ScanFile call reads the number of elements into the integer variable count. If the value in count exceeds the number of elements in the real array values, an error is reported. Otherwise, the second ScanFile call matches count to the asterisk (*) in the format string. It
LabWindows/CVI Standard Libraries 2-68 © National Instruments Corporation
Chapter 2 Formatting and I/O Library
then reads the correct number of elements into values. The x modifier causes the comma separators to be discarded.

Binary File to Integer Array, Assuming a Fixed Number of Elements

int readings[100]; int file_handle, nbytes; file_handle = OpenFile ("FILE.DAT", 1, 2, 0); ScanFile (file_handle, "%100i>%100i", readings); nbytes = NumFmtdBytes (); CloseFile (file_handle);
Remarks
The ScanFile call reads 100 integers from a binary file and stores them in the integer array readings. If the ScanFile call is successful, nbytes = 200 (100 integers, 2 bytes per
integer).

Binary File to Real Array, Assuming a Fixed Number of Elements

double waveform[100]; int file_handle, nbytes; file_handle = OpenFile ("FILE.DAT", 1, 2, 0); ScanFile (file_handle, "%100f>%100f", waveform); nbytes = NumFmtdBytes (); CloseFile (file_handle);
Remarks
The ScanFile call reads 100 real numbers from a binary file and stores them in the real array waveform. If the ScanFile call is successful, nbytes = 800 (100 integers, 8 bytes per real
number).

Binary File to Real Array, Assuming a Variable Number of Elements

void StoreArray (double x[], int count, char filename[])
{
int file_handle;
file_handle = OpenFile (filename, 1, 2, 0);
ScanFile (file_handle, "%*f>%*f", count, count, x);
CloseFile (file_handle);
}
© National Instruments Corporation 2-69 LabWindows/CVI Standard Libraries
Formatting and I/O Library Chapter 2
Remarks
This example shows how a subroutine can be used to read an array of real numbers from a binary file. The subroutine takes as parameters a real array, the number of elements to be read, and the filename.
The ScanFile call reads the first count elements of x from a binary file. The two asterisks (*) in the format string are matched to count. For instance, if count is 100, then the format string is equivalent to %100f>100f.

Reading an Integer from the Standard Input

int n, num_readings; n = 0; while (n != 1) {
FmtOut ("Enter number of readings: ");
n = ScanIn ("%l>%i", &num_readings); }
Remarks
This example shows how to get user input from the keyboard. The FmtOut call writes the prompt string to the screen without a linefeed or carriage return. The ScanIn call attempts to read an integer value from the keyboard and place it in num_readings. If ScanIn succeeds, it returns 1, and the loop is exited. Otherwise, the prompt string is repeated.
The format string in the ScanIn call contains a source specifier of %l. This has two consequences. First, ScanIn returns whenever the user presses ENTER, even if the input line is empty. This allows the prompt string to be repeated at the beginning of each line until the user enters an integer value. Second, any characters entered after the integer value are discarded.

Reading a String from the Standard Input

char filename[41]; int n; n = 0; while (n != 1) {
FmtOut ("Enter file name: ");
n = ScanIn ("%l>%s[w40q]", filename); }
Remarks
This example is similar to the previous example, except that the item being read from the keyboard is a string instead of an integer. The w modifier is used to prevent ScanIn from
LabWindows/CVI Standard Libraries 2-70 © National Instruments Corporation
Loading...