6504 Bridge Point ParkwayAustin, TX 78730-5039Tel: (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.
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 Startedwith 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.
•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 FunctionReference 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 FunctionReference 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.
The following conventions are used in this manual:
About This Manual
bold
italicItalic text denotes emphasis, a cross reference, or an introduction to
bold italicBold italic text denotes a note, caution, or warning.
monospaceText 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.
pathsPaths 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
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 toLabWindows/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.
•Gettys, James and Robert W. Scheifler. Xlib—C Language X Interface, MIT X ConsortiumStandard. 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
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.
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, 40
1, 5, 8, 91
3, 7, 102
63
24
For the LC_CTYPE locale:
•isalnum maps to the Windows function isCharAlphaNumeric.
•isalpha maps to the Windows function isCharAlpha.
•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.
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.
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
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.
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
integerFile handle returned by open or sopen.
stringSpecifies the read/write, binary/text, and append modes.
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 tofwrite fails.
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 FunctionPanels for the Formatting and Scanning Functions section later in this chapter for more
information.
Table 2-1. The Formatting and I/O Library Function Tree
Formatting and I/O
File I/O
Open FileOpenFile
Close FileCloseFile
Read from FileReadFile
Write to FileWriteFile
Array to FileArrayToFile
File to ArrayFileToArray
Get File InformationGetFileInfo
Set File PointerSetFilePtr
String Manipulation
Get String LengthStringLength
String to LowercaseStringLowerCase
String to UppercaseStringUpperCase
Fill BytesFillBytes
Copy BytesCopyBytes
Copy StringCopyString
Compare BytesCompareBytes
Compare StringsCompareStrings
Find PatternFindPattern
Read LineReadLine
Write LineWriteLine
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 BytesNumFmtdBytes
Get Format Index ErrorGetFmtErrNdx
Get I/O ErrorGetFmtIOError
Get I/O Error StringGetFmtIOErrorString
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.
•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
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.
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.
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
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
integerStarting position in
targetBuffer.
sourceBuffer
sourceIndex
stringSource buffer.
integerStarting position in
sourceBuffer.
integerNumber of bytes to copy.
stringDestination buffer.
integerNumber of bytes to copy, excluding the ASCII
NUL.
Output
targetString
stringDestination 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
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.
stringFile pathname.
integerArray element data type.
integerNumber of elements in array.
integerNumber of Groups in array.
integerHow groups are ordered in file.
integerDirection to write groups in file.
integerASCII/binary mode.
void*Numeric array.
,
,
ArrayToFile
Return Value
status
Return Code
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
integerIndicates 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
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.
stringBuffer to be searched.
integer
integerNumber of bytes to search.
stringPattern to search for.
integerCase-sensitivity mode.
integerDirection of search.
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:
source1,…,sourcenTypes must match formatString contents.
Output
targetType must match formatString contents.
Return Value
n
integerNumber 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,…,sourcentypes must match formatString
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,…,sourcenTypes must match formatString contents.
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
stringPathname of the file to be
checked.
Output
fileSize
longFile size or zero.
Return Value
status
integerIndicates 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)
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
integerPosition 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,
0No error.
1File not found.
2General I/O error.
3Invalid file handle.
4Not enough memory.
5File already exists.
6Permission denied.
7Invalid argument.
8Maximum number of files open.
9Disk is full.
10File name is too long.
GetFmtIOErrorString
char *message = GetFmtIOErrorString (int errorNum);
Purpose
Converts the error number returned by GetLastFmtIOError into a meaningful error message.
Parameters
Returns the number of bytes formatted or scanned by the previous formatting or scanning call.
Parameters
None
Return Value
n
integerNumber 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. */
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 ifread/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
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, CRLF combination translates to LF when reading, and LF
translates to CRLF 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
integerFile handle.
integerNumber of bytes to read.
stringInput buffer.
Return Value
n
integerNumber 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.
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
integerFile handle.
integerMaximum number of bytes to
read into line, excluding the
ASCII NUL.
stringInput buffer.
integerNumber 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
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
sourceType must match formatString contents
formatString
string.
targetptr1,…,targetptrnTypes must match formatString contents.
Return Value
n
integerNumber 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
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
integerNumber 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,…,targetptrnTypes must match formatString contents.
String.
Return Value
n
integerNumber 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 theFormatting 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
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){
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.
stringData buffer.
integerNumber of bytes to write.
integerNumber 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
integerFile handle.
stringData buffer.
integerNumber of bytes to write.
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.
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);
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 functionFmtOut, 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.
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.
freal 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.
ccharacter. 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)
bnSpecify 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.
inSpecify 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.
zTreat 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.
rnSpecify 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).
wnSpecify 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
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.
pcSpecify 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.
sSpecify 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.
uSpecify as Unsigned. The u integer modifier indicates that the integer is
considered an unsigned integer.
onnnnSpecify 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.
Note: When using both the bn and on modifiers on an integer specifier, the bn modifier
must be first.
Formatting Floating-Point Modifiers (%f)
bnSpecify 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.
zTreat 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.
wnSpecify 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.
pnSpecify 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.
enSpecify 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.
fSpecify 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.
tTruncate. 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.
rRound. 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 emodifier 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)
inSpecify 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 zerobased 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.
aAppend. 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.
wnSpecify 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.
qAppend 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.
tnTerminate 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:
repFor integer or floating-point arrays
inFor integer or floating-point arrays, or strings
wnFor any format specifier
pnFor floating-point specifiers only
enFor floating-point specifiers only
rnFor 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.
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.
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.
formatcode is specified with one of the following codes:
sstring. 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.
lstring. 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.
iinteger. 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.
xinteger (hexadecimal). This specifier indicates a %i format with hexadecimal radix.
ointeger (octal). This specifier indicates a %i format with octal radix.
dinteger (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.
freal 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.
ccharacter. 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)
bnSpecify 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.
inSpecify 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.
zTreat 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.
rnSpecify 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).
wnSpecify 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.
sSpecify 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.
uSpecify as Non-negative. The u integer modifier indicates that the integer is to be
considered a non-negative integer.
xDiscard 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.
dDiscard 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.
onnnnSpecify 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.
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.
If the pn modifier is omitted, a default of p6 is used. The p modifier is valid for
sources only.
enSpecify 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.
fSpecify 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.
xDiscard 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 floatingpoint 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.
dDiscard 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)
inSpecify 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 zerobased 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.
aAppend. 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.
wnSpecify 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
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.
qAppend 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.
yAppend 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.
tnTerminate 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.
xDiscard 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.
dDiscard 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.
repFor integer or floating-point arrays.
inFor integer or floating-point arrays, or strings.
wnFor any format specifier.
pnFor floating-point specifiers only.
enFor floating-point specifiers only.
rnFor 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.
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
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 toASCII 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;
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++) {
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[])
{
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
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 withError 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 */
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 */
When locating a real number in a string, Scan skips over white space characters. If a nonnumeric 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).
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.
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.
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.
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
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
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
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.
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
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, thei6 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
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.
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
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
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
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[])
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