stdio.texi 234 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669
  1. @node I/O on Streams, Low-Level I/O, I/O Overview, Top
  2. @c %MENU% High-level, portable I/O facilities
  3. @chapter Input/Output on Streams
  4. @c fix an overfull:
  5. @tex
  6. \hyphenation{which-ever}
  7. @end tex
  8. This chapter describes the functions for creating streams and performing
  9. input and output operations on them. As discussed in @ref{I/O
  10. Overview}, a stream is a fairly abstract, high-level concept
  11. representing a communications channel to a file, device, or process.
  12. @menu
  13. * Streams:: About the data type representing a stream.
  14. * Standard Streams:: Streams to the standard input and output
  15. devices are created for you.
  16. * Opening Streams:: How to create a stream to talk to a file.
  17. * Closing Streams:: Close a stream when you are finished with it.
  18. * Streams and Threads:: Issues with streams in threaded programs.
  19. * Streams and I18N:: Streams in internationalized applications.
  20. * Simple Output:: Unformatted output by characters and lines.
  21. * Character Input:: Unformatted input by characters and words.
  22. * Line Input:: Reading a line or a record from a stream.
  23. * Unreading:: Peeking ahead/pushing back input just read.
  24. * Block Input/Output:: Input and output operations on blocks of data.
  25. * Formatted Output:: @code{printf} and related functions.
  26. * Customizing Printf:: You can define new conversion specifiers for
  27. @code{printf} and friends.
  28. * Formatted Input:: @code{scanf} and related functions.
  29. * EOF and Errors:: How you can tell if an I/O error happens.
  30. * Error Recovery:: What you can do about errors.
  31. * Binary Streams:: Some systems distinguish between text files
  32. and binary files.
  33. * File Positioning:: About random-access streams.
  34. * Portable Positioning:: Random access on peculiar ISO C systems.
  35. * Stream Buffering:: How to control buffering of streams.
  36. * Other Kinds of Streams:: Streams that do not necessarily correspond
  37. to an open file.
  38. * Formatted Messages:: Print strictly formatted messages.
  39. @end menu
  40. @node Streams
  41. @section Streams
  42. For historical reasons, the type of the C data structure that represents
  43. a stream is called @code{FILE} rather than ``stream''. Since most of
  44. the library functions deal with objects of type @code{FILE *}, sometimes
  45. the term @dfn{file pointer} is also used to mean ``stream''. This leads
  46. to unfortunate confusion over terminology in many books on C. This
  47. manual, however, is careful to use the terms ``file'' and ``stream''
  48. only in the technical sense.
  49. @cindex file pointer
  50. @pindex stdio.h
  51. The @code{FILE} type is declared in the header file @file{stdio.h}.
  52. @deftp {Data Type} FILE
  53. @standards{ISO, stdio.h}
  54. This is the data type used to represent stream objects. A @code{FILE}
  55. object holds all of the internal state information about the connection
  56. to the associated file, including such things as the file position
  57. indicator and buffering information. Each stream also has error and
  58. end-of-file status indicators that can be tested with the @code{ferror}
  59. and @code{feof} functions; see @ref{EOF and Errors}.
  60. @end deftp
  61. @code{FILE} objects are allocated and managed internally by the
  62. input/output library functions. Don't try to create your own objects of
  63. type @code{FILE}; let the library do it. Your programs should
  64. deal only with pointers to these objects (that is, @code{FILE *} values)
  65. rather than the objects themselves.
  66. @c !!! should say that FILE's have "No user-serviceable parts inside."
  67. @node Standard Streams
  68. @section Standard Streams
  69. @cindex standard streams
  70. @cindex streams, standard
  71. When the @code{main} function of your program is invoked, it already has
  72. three predefined streams open and available for use. These represent
  73. the ``standard'' input and output channels that have been established
  74. for the process.
  75. These streams are declared in the header file @file{stdio.h}.
  76. @pindex stdio.h
  77. @deftypevar {FILE *} stdin
  78. @standards{ISO, stdio.h}
  79. The @dfn{standard input} stream, which is the normal source of input for the
  80. program.
  81. @end deftypevar
  82. @cindex standard input stream
  83. @deftypevar {FILE *} stdout
  84. @standards{ISO, stdio.h}
  85. The @dfn{standard output} stream, which is used for normal output from
  86. the program.
  87. @end deftypevar
  88. @cindex standard output stream
  89. @deftypevar {FILE *} stderr
  90. @standards{ISO, stdio.h}
  91. The @dfn{standard error} stream, which is used for error messages and
  92. diagnostics issued by the program.
  93. @end deftypevar
  94. @cindex standard error stream
  95. On @gnusystems{}, you can specify what files or processes correspond to
  96. these streams using the pipe and redirection facilities provided by the
  97. shell. (The primitives shells use to implement these facilities are
  98. described in @ref{File System Interface}.) Most other operating systems
  99. provide similar mechanisms, but the details of how to use them can vary.
  100. In @theglibc{}, @code{stdin}, @code{stdout}, and @code{stderr} are
  101. normal variables which you can set just like any others. For example,
  102. to redirect the standard output to a file, you could do:
  103. @smallexample
  104. fclose (stdout);
  105. stdout = fopen ("standard-output-file", "w");
  106. @end smallexample
  107. Note however, that in other systems @code{stdin}, @code{stdout}, and
  108. @code{stderr} are macros that you cannot assign to in the normal way.
  109. But you can use @code{freopen} to get the effect of closing one and
  110. reopening it. @xref{Opening Streams}.
  111. The three streams @code{stdin}, @code{stdout}, and @code{stderr} are not
  112. unoriented at program start (@pxref{Streams and I18N}).
  113. @node Opening Streams
  114. @section Opening Streams
  115. @cindex opening a stream
  116. Opening a file with the @code{fopen} function creates a new stream and
  117. establishes a connection between the stream and a file. This may
  118. involve creating a new file.
  119. @pindex stdio.h
  120. Everything described in this section is declared in the header file
  121. @file{stdio.h}.
  122. @deftypefun {FILE *} fopen (const char *@var{filename}, const char *@var{opentype})
  123. @standards{ISO, stdio.h}
  124. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
  125. @c fopen may leak the list lock if cancelled within _IO_link_in.
  126. The @code{fopen} function opens a stream for I/O to the file
  127. @var{filename}, and returns a pointer to the stream.
  128. The @var{opentype} argument is a string that controls how the file is
  129. opened and specifies attributes of the resulting stream. It must begin
  130. with one of the following sequences of characters:
  131. @table @samp
  132. @item r
  133. Open an existing file for reading only.
  134. @item w
  135. Open the file for writing only. If the file already exists, it is
  136. truncated to zero length. Otherwise a new file is created.
  137. @item a
  138. Open a file for append access; that is, writing at the end of file only.
  139. If the file already exists, its initial contents are unchanged and
  140. output to the stream is appended to the end of the file.
  141. Otherwise, a new, empty file is created.
  142. @item r+
  143. Open an existing file for both reading and writing. The initial contents
  144. of the file are unchanged and the initial file position is at the
  145. beginning of the file.
  146. @item w+
  147. Open a file for both reading and writing. If the file already exists, it
  148. is truncated to zero length. Otherwise, a new file is created.
  149. @item a+
  150. Open or create file for both reading and appending. If the file exists,
  151. its initial contents are unchanged. Otherwise, a new file is created.
  152. The initial file position for reading is at the beginning of the file,
  153. but output is always appended to the end of the file.
  154. @end table
  155. As you can see, @samp{+} requests a stream that can do both input and
  156. output. When using such a stream, you must call @code{fflush}
  157. (@pxref{Stream Buffering}) or a file positioning function such as
  158. @code{fseek} (@pxref{File Positioning}) when switching from reading
  159. to writing or vice versa. Otherwise, internal buffers might not be
  160. emptied properly.
  161. Additional characters may appear after these to specify flags for the
  162. call. Always put the mode (@samp{r}, @samp{w+}, etc.) first; that is
  163. the only part you are guaranteed will be understood by all systems.
  164. @Theglibc{} defines additional characters for use in @var{opentype}:
  165. @table @samp
  166. @item c
  167. The file is opened with cancellation in the I/O functions disabled.
  168. @item e
  169. The underlying file descriptor will be closed if you use any of the
  170. @code{exec@dots{}} functions (@pxref{Executing a File}). (This is
  171. equivalent to having set @code{FD_CLOEXEC} on that descriptor.
  172. @xref{Descriptor Flags}.)
  173. @item m
  174. The file is opened and accessed using @code{mmap}. This is only
  175. supported with files opened for reading.
  176. @item x
  177. Insist on creating a new file---if a file @var{filename} already
  178. exists, @code{fopen} fails rather than opening it. If you use
  179. @samp{x} you are guaranteed that you will not clobber an existing
  180. file. This is equivalent to the @code{O_EXCL} option to the
  181. @code{open} function (@pxref{Opening and Closing Files}).
  182. The @samp{x} modifier is part of @w{ISO C11}, which says the file is
  183. created with exclusive access; in @theglibc{} this means the
  184. equivalent of @code{O_EXCL}.
  185. @end table
  186. The character @samp{b} in @var{opentype} has a standard meaning; it
  187. requests a binary stream rather than a text stream. But this makes no
  188. difference in POSIX systems (including @gnusystems{}). If both
  189. @samp{+} and @samp{b} are specified, they can appear in either order.
  190. @xref{Binary Streams}.
  191. @cindex stream orientation
  192. @cindex orientation, stream
  193. If the @var{opentype} string contains the sequence
  194. @code{,ccs=@var{STRING}} then @var{STRING} is taken as the name of a
  195. coded character set and @code{fopen} will mark the stream as
  196. wide-oriented with appropriate conversion functions in place to convert
  197. from and to the character set @var{STRING}. Any other stream
  198. is opened initially unoriented and the orientation is decided with the
  199. first file operation. If the first operation is a wide character
  200. operation, the stream is not only marked as wide-oriented, also the
  201. conversion functions to convert to the coded character set used for the
  202. current locale are loaded. This will not change anymore from this point
  203. on even if the locale selected for the @code{LC_CTYPE} category is
  204. changed.
  205. Any other characters in @var{opentype} are simply ignored. They may be
  206. meaningful in other systems.
  207. If the open fails, @code{fopen} returns a null pointer.
  208. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  209. 32 bit machine this function is in fact @code{fopen64} since the LFS
  210. interface replaces transparently the old interface.
  211. @end deftypefun
  212. You can have multiple streams (or file descriptors) pointing to the same
  213. file open at the same time. If you do only input, this works
  214. straightforwardly, but you must be careful if any output streams are
  215. included. @xref{Stream/Descriptor Precautions}. This is equally true
  216. whether the streams are in one program (not usual) or in several
  217. programs (which can easily happen). It may be advantageous to use the
  218. file locking facilities to avoid simultaneous access. @xref{File
  219. Locks}.
  220. @deftypefun {FILE *} fopen64 (const char *@var{filename}, const char *@var{opentype})
  221. @standards{Unix98, stdio.h}
  222. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
  223. This function is similar to @code{fopen} but the stream it returns a
  224. pointer for is opened using @code{open64}. Therefore this stream can be
  225. used even on files larger than @twoexp{31} bytes on 32 bit machines.
  226. Please note that the return type is still @code{FILE *}. There is no
  227. special @code{FILE} type for the LFS interface.
  228. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
  229. bits machine this function is available under the name @code{fopen}
  230. and so transparently replaces the old interface.
  231. @end deftypefun
  232. @deftypevr Macro int FOPEN_MAX
  233. @standards{ISO, stdio.h}
  234. The value of this macro is an integer constant expression that
  235. represents the minimum number of streams that the implementation
  236. guarantees can be open simultaneously. You might be able to open more
  237. than this many streams, but that is not guaranteed. The value of this
  238. constant is at least eight, which includes the three standard streams
  239. @code{stdin}, @code{stdout}, and @code{stderr}. In POSIX.1 systems this
  240. value is determined by the @code{OPEN_MAX} parameter; @pxref{General
  241. Limits}. In BSD and GNU, it is controlled by the @code{RLIMIT_NOFILE}
  242. resource limit; @pxref{Limits on Resources}.
  243. @end deftypevr
  244. @deftypefun {FILE *} freopen (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream})
  245. @standards{ISO, stdio.h}
  246. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @acsfd{}}}
  247. @c Like most I/O operations, this one is guarded by a recursive lock,
  248. @c released even upon cancellation, but cancellation may leak file
  249. @c descriptors and leave the stream in an inconsistent state (e.g.,
  250. @c still bound to the closed descriptor). Also, if the stream is
  251. @c part-way through a significant update (say running freopen) when a
  252. @c signal handler calls freopen again on the same stream, the result is
  253. @c likely to be an inconsistent stream, and the possibility of closing
  254. @c twice file descriptor number that the stream used to use, the second
  255. @c time when it might have already been reused by another thread.
  256. This function is like a combination of @code{fclose} and @code{fopen}.
  257. It first closes the stream referred to by @var{stream}, ignoring any
  258. errors that are detected in the process. (Because errors are ignored,
  259. you should not use @code{freopen} on an output stream if you have
  260. actually done any output using the stream.) Then the file named by
  261. @var{filename} is opened with mode @var{opentype} as for @code{fopen},
  262. and associated with the same stream object @var{stream}.
  263. If the operation fails, a null pointer is returned; otherwise,
  264. @code{freopen} returns @var{stream}. On Linux, @code{freopen} may also
  265. fail and set @code{errno} to @code{EBUSY} when the kernel structure for
  266. the old file descriptor was not initialized completely before @code{freopen}
  267. was called. This can only happen in multi-threaded programs, when two
  268. threads race to allocate the same file descriptor number. To avoid the
  269. possibility of this race, do not use @code{close} to close the underlying
  270. file descriptor for a @code{FILE}; either use @code{freopen} while the
  271. file is still open, or use @code{open} and then @code{dup2} to install
  272. the new file descriptor.
  273. @code{freopen} has traditionally been used to connect a standard stream
  274. such as @code{stdin} with a file of your own choice. This is useful in
  275. programs in which use of a standard stream for certain purposes is
  276. hard-coded. In @theglibc{}, you can simply close the standard
  277. streams and open new ones with @code{fopen}. But other systems lack
  278. this ability, so using @code{freopen} is more portable.
  279. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  280. 32 bit machine this function is in fact @code{freopen64} since the LFS
  281. interface replaces transparently the old interface.
  282. @Theglibc{} only supports use of @code{freopen} on streams opened with
  283. @code{fopen} or @code{fopen64} and on the original values of the
  284. standard streams @code{stdin}, @code{stdout}, and @code{stderr}; such
  285. a stream may be reopened multiple times with @code{freopen}. If it is
  286. called on another kind of stream (opened with functions such as
  287. @code{popen}, @code{fmemopen}, @code{open_memstream}, and
  288. @code{fopencookie}), @code{freopen} fails and returns a null pointer.
  289. @end deftypefun
  290. @deftypefun {FILE *} freopen64 (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream})
  291. @standards{Unix98, stdio.h}
  292. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @acsfd{}}}
  293. This function is similar to @code{freopen}. The only difference is that
  294. on 32 bit machine the stream returned is able to read beyond the
  295. @twoexp{31} bytes limits imposed by the normal interface. It should be
  296. noted that the stream pointed to by @var{stream} need not be opened
  297. using @code{fopen64} or @code{freopen64} since its mode is not important
  298. for this function.
  299. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
  300. bits machine this function is available under the name @code{freopen}
  301. and so transparently replaces the old interface.
  302. @end deftypefun
  303. In some situations it is useful to know whether a given stream is
  304. available for reading or writing. This information is normally not
  305. available and would have to be remembered separately. Solaris
  306. introduced a few functions to get this information from the stream
  307. descriptor and these functions are also available in @theglibc{}.
  308. @deftypefun int __freadable (FILE *@var{stream})
  309. @standards{GNU, stdio_ext.h}
  310. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  311. The @code{__freadable} function determines whether the stream
  312. @var{stream} was opened to allow reading. In this case the return value
  313. is nonzero. For write-only streams the function returns zero.
  314. This function is declared in @file{stdio_ext.h}.
  315. @end deftypefun
  316. @deftypefun int __fwritable (FILE *@var{stream})
  317. @standards{GNU, stdio_ext.h}
  318. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  319. The @code{__fwritable} function determines whether the stream
  320. @var{stream} was opened to allow writing. In this case the return value
  321. is nonzero. For read-only streams the function returns zero.
  322. This function is declared in @file{stdio_ext.h}.
  323. @end deftypefun
  324. For slightly different kinds of problems there are two more functions.
  325. They provide even finer-grained information.
  326. @deftypefun int __freading (FILE *@var{stream})
  327. @standards{GNU, stdio_ext.h}
  328. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  329. The @code{__freading} function determines whether the stream
  330. @var{stream} was last read from or whether it is opened read-only. In
  331. this case the return value is nonzero, otherwise it is zero.
  332. Determining whether a stream opened for reading and writing was last
  333. used for writing allows to draw conclusions about the content about the
  334. buffer, among other things.
  335. This function is declared in @file{stdio_ext.h}.
  336. @end deftypefun
  337. @deftypefun int __fwriting (FILE *@var{stream})
  338. @standards{GNU, stdio_ext.h}
  339. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  340. The @code{__fwriting} function determines whether the stream
  341. @var{stream} was last written to or whether it is opened write-only. In
  342. this case the return value is nonzero, otherwise it is zero.
  343. This function is declared in @file{stdio_ext.h}.
  344. @end deftypefun
  345. @node Closing Streams
  346. @section Closing Streams
  347. @cindex closing a stream
  348. When a stream is closed with @code{fclose}, the connection between the
  349. stream and the file is canceled. After you have closed a stream, you
  350. cannot perform any additional operations on it.
  351. @deftypefun int fclose (FILE *@var{stream})
  352. @standards{ISO, stdio.h}
  353. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
  354. @c After fclose, it is undefined behavior to use the stream it points
  355. @c to. Therefore, one must only call fclose when the stream is
  356. @c otherwise unused. Concurrent uses started before will complete
  357. @c successfully because of the lock, which makes it MT-Safe. Calling it
  358. @c from a signal handler is perfectly safe if the stream is known to be
  359. @c no longer used, which is a precondition for fclose to be safe in the
  360. @c first place; since this is no further requirement, fclose is safe for
  361. @c use in async signals too. After calling fclose, you can no longer
  362. @c use the stream, not even to fclose it again, so its memory and file
  363. @c descriptor may leak if fclose is canceled before @c releasing them.
  364. @c That the stream must be unused and it becomes unused after the call
  365. @c is what would enable fclose to be AS- and AC-Safe while freopen
  366. @c isn't. However, because of the possibility of leaving __gconv_lock
  367. @c taken upon cancellation, AC-Safety is lost.
  368. This function causes @var{stream} to be closed and the connection to
  369. the corresponding file to be broken. Any buffered output is written
  370. and any buffered input is discarded. The @code{fclose} function returns
  371. a value of @code{0} if the file was closed successfully, and @code{EOF}
  372. if an error was detected.
  373. It is important to check for errors when you call @code{fclose} to close
  374. an output stream, because real, everyday errors can be detected at this
  375. time. For example, when @code{fclose} writes the remaining buffered
  376. output, it might get an error because the disk is full. Even if you
  377. know the buffer is empty, errors can still occur when closing a file if
  378. you are using NFS.
  379. The function @code{fclose} is declared in @file{stdio.h}.
  380. @end deftypefun
  381. To close all streams currently available @theglibc{} provides
  382. another function.
  383. @deftypefun int fcloseall (void)
  384. @standards{GNU, stdio.h}
  385. @safety{@prelim{}@mtunsafe{@mtasurace{:streams}}@asunsafe{}@acsafe{}}
  386. @c Like fclose, using any previously-opened streams after fcloseall is
  387. @c undefined. However, the implementation of fcloseall isn't equivalent
  388. @c to calling fclose for all streams: it just flushes and unbuffers all
  389. @c streams, without any locking. It's the flushing without locking that
  390. @c makes it unsafe.
  391. This function causes all open streams of the process to be closed and
  392. the connections to corresponding files to be broken. All buffered data
  393. is written and any buffered input is discarded. The @code{fcloseall}
  394. function returns a value of @code{0} if all the files were closed
  395. successfully, and @code{EOF} if an error was detected.
  396. This function should be used only in special situations, e.g., when an
  397. error occurred and the program must be aborted. Normally each single
  398. stream should be closed separately so that problems with individual
  399. streams can be identified. It is also problematic since the standard
  400. streams (@pxref{Standard Streams}) will also be closed.
  401. The function @code{fcloseall} is declared in @file{stdio.h}.
  402. @end deftypefun
  403. If the @code{main} function to your program returns, or if you call the
  404. @code{exit} function (@pxref{Normal Termination}), all open streams are
  405. automatically closed properly. If your program terminates in any other
  406. manner, such as by calling the @code{abort} function (@pxref{Aborting a
  407. Program}) or from a fatal signal (@pxref{Signal Handling}), open streams
  408. might not be closed properly. Buffered output might not be flushed and
  409. files may be incomplete. For more information on buffering of streams,
  410. see @ref{Stream Buffering}.
  411. @node Streams and Threads
  412. @section Streams and Threads
  413. @cindex threads
  414. @cindex multi-threaded application
  415. Streams can be used in multi-threaded applications in the same way they
  416. are used in single-threaded applications. But the programmer must be
  417. aware of the possible complications. It is important to know about
  418. these also if the program one writes never use threads since the design
  419. and implementation of many stream functions are heavily influenced by the
  420. requirements added by multi-threaded programming.
  421. The POSIX standard requires that by default the stream operations are
  422. atomic. I.e., issuing two stream operations for the same stream in two
  423. threads at the same time will cause the operations to be executed as if
  424. they were issued sequentially. The buffer operations performed while
  425. reading or writing are protected from other uses of the same stream. To
  426. do this each stream has an internal lock object which has to be
  427. (implicitly) acquired before any work can be done.
  428. But there are situations where this is not enough and there are also
  429. situations where this is not wanted. The implicit locking is not enough
  430. if the program requires more than one stream function call to happen
  431. atomically. One example would be if an output line a program wants to
  432. generate is created by several function calls. The functions by
  433. themselves would ensure only atomicity of their own operation, but not
  434. atomicity over all the function calls. For this it is necessary to
  435. perform the stream locking in the application code.
  436. @deftypefun void flockfile (FILE *@var{stream})
  437. @standards{POSIX, stdio.h}
  438. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
  439. @c There's no way to tell whether the lock was acquired before or after
  440. @c cancellation so as to unlock only when appropriate.
  441. The @code{flockfile} function acquires the internal locking object
  442. associated with the stream @var{stream}. This ensures that no other
  443. thread can explicitly through @code{flockfile}/@code{ftrylockfile} or
  444. implicitly through the call of a stream function lock the stream. The
  445. thread will block until the lock is acquired. An explicit call to
  446. @code{funlockfile} has to be used to release the lock.
  447. @end deftypefun
  448. @deftypefun int ftrylockfile (FILE *@var{stream})
  449. @standards{POSIX, stdio.h}
  450. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
  451. The @code{ftrylockfile} function tries to acquire the internal locking
  452. object associated with the stream @var{stream} just like
  453. @code{flockfile}. But unlike @code{flockfile} this function does not
  454. block if the lock is not available. @code{ftrylockfile} returns zero if
  455. the lock was successfully acquired. Otherwise the stream is locked by
  456. another thread.
  457. @end deftypefun
  458. @deftypefun void funlockfile (FILE *@var{stream})
  459. @standards{POSIX, stdio.h}
  460. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
  461. The @code{funlockfile} function releases the internal locking object of
  462. the stream @var{stream}. The stream must have been locked before by a
  463. call to @code{flockfile} or a successful call of @code{ftrylockfile}.
  464. The implicit locking performed by the stream operations do not count.
  465. The @code{funlockfile} function does not return an error status and the
  466. behavior of a call for a stream which is not locked by the current
  467. thread is undefined.
  468. @end deftypefun
  469. The following example shows how the functions above can be used to
  470. generate an output line atomically even in multi-threaded applications
  471. (yes, the same job could be done with one @code{fprintf} call but it is
  472. sometimes not possible):
  473. @smallexample
  474. FILE *fp;
  475. @{
  476. @dots{}
  477. flockfile (fp);
  478. fputs ("This is test number ", fp);
  479. fprintf (fp, "%d\n", test);
  480. funlockfile (fp)
  481. @}
  482. @end smallexample
  483. Without the explicit locking it would be possible for another thread to
  484. use the stream @var{fp} after the @code{fputs} call returns and before
  485. @code{fprintf} was called with the result that the number does not
  486. follow the word @samp{number}.
  487. From this description it might already be clear that the locking objects
  488. in streams are no simple mutexes. Since locking the same stream twice
  489. in the same thread is allowed the locking objects must be equivalent to
  490. recursive mutexes. These mutexes keep track of the owner and the number
  491. of times the lock is acquired. The same number of @code{funlockfile}
  492. calls by the same threads is necessary to unlock the stream completely.
  493. For instance:
  494. @smallexample
  495. void
  496. foo (FILE *fp)
  497. @{
  498. ftrylockfile (fp);
  499. fputs ("in foo\n", fp);
  500. /* @r{This is very wrong!!!} */
  501. funlockfile (fp);
  502. @}
  503. @end smallexample
  504. It is important here that the @code{funlockfile} function is only called
  505. if the @code{ftrylockfile} function succeeded in locking the stream. It
  506. is therefore always wrong to ignore the result of @code{ftrylockfile}.
  507. And it makes no sense since otherwise one would use @code{flockfile}.
  508. The result of code like that above is that either @code{funlockfile}
  509. tries to free a stream that hasn't been locked by the current thread or it
  510. frees the stream prematurely. The code should look like this:
  511. @smallexample
  512. void
  513. foo (FILE *fp)
  514. @{
  515. if (ftrylockfile (fp) == 0)
  516. @{
  517. fputs ("in foo\n", fp);
  518. funlockfile (fp);
  519. @}
  520. @}
  521. @end smallexample
  522. Now that we covered why it is necessary to have locking it is
  523. necessary to talk about situations when locking is unwanted and what can
  524. be done. The locking operations (explicit or implicit) don't come for
  525. free. Even if a lock is not taken the cost is not zero. The operations
  526. which have to be performed require memory operations that are safe in
  527. multi-processor environments. With the many local caches involved in
  528. such systems this is quite costly. So it is best to avoid the locking
  529. completely if it is not needed -- because the code in question is never
  530. used in a context where two or more threads may use a stream at a time.
  531. This can be determined most of the time for application code; for
  532. library code which can be used in many contexts one should default to be
  533. conservative and use locking.
  534. There are two basic mechanisms to avoid locking. The first is to use
  535. the @code{_unlocked} variants of the stream operations. The POSIX
  536. standard defines quite a few of those and @theglibc{} adds a few
  537. more. These variants of the functions behave just like the functions
  538. with the name without the suffix except that they do not lock the
  539. stream. Using these functions is very desirable since they are
  540. potentially much faster. This is not only because the locking
  541. operation itself is avoided. More importantly, functions like
  542. @code{putc} and @code{getc} are very simple and traditionally (before the
  543. introduction of threads) were implemented as macros which are very fast
  544. if the buffer is not empty. With the addition of locking requirements
  545. these functions are no longer implemented as macros since they would
  546. expand to too much code.
  547. But these macros are still available with the same functionality under the new
  548. names @code{putc_unlocked} and @code{getc_unlocked}. This possibly huge
  549. difference of speed also suggests the use of the @code{_unlocked}
  550. functions even if locking is required. The difference is that the
  551. locking then has to be performed in the program:
  552. @smallexample
  553. void
  554. foo (FILE *fp, char *buf)
  555. @{
  556. flockfile (fp);
  557. while (*buf != '/')
  558. putc_unlocked (*buf++, fp);
  559. funlockfile (fp);
  560. @}
  561. @end smallexample
  562. If in this example the @code{putc} function would be used and the
  563. explicit locking would be missing the @code{putc} function would have to
  564. acquire the lock in every call, potentially many times depending on when
  565. the loop terminates. Writing it the way illustrated above allows the
  566. @code{putc_unlocked} macro to be used which means no locking and direct
  567. manipulation of the buffer of the stream.
  568. A second way to avoid locking is by using a non-standard function which
  569. was introduced in Solaris and is available in @theglibc{} as well.
  570. @deftypefun int __fsetlocking (FILE *@var{stream}, int @var{type})
  571. @standards{GNU, stdio_ext.h}
  572. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asulock{}}@acsafe{}}
  573. @c Changing the implicit-locking status of a stream while it's in use by
  574. @c another thread may cause a lock to be implicitly acquired and not
  575. @c released, or vice-versa. This function should probably hold the lock
  576. @c while changing this setting, to make sure we don't change it while
  577. @c there are any concurrent uses. Meanwhile, callers should acquire the
  578. @c lock themselves to be safe, and even concurrent uses with external
  579. @c locking will be fine, as long as functions that require external
  580. @c locking are not called without holding locks.
  581. The @code{__fsetlocking} function can be used to select whether the
  582. stream operations will implicitly acquire the locking object of the
  583. stream @var{stream}. By default this is done but it can be disabled and
  584. reinstated using this function. There are three values defined for the
  585. @var{type} parameter.
  586. @vtable @code
  587. @item FSETLOCKING_INTERNAL
  588. The stream @code{stream} will from now on use the default internal
  589. locking. Every stream operation with exception of the @code{_unlocked}
  590. variants will implicitly lock the stream.
  591. @item FSETLOCKING_BYCALLER
  592. After the @code{__fsetlocking} function returns, the user is responsible
  593. for locking the stream. None of the stream operations will implicitly
  594. do this anymore until the state is set back to
  595. @code{FSETLOCKING_INTERNAL}.
  596. @item FSETLOCKING_QUERY
  597. @code{__fsetlocking} only queries the current locking state of the
  598. stream. The return value will be @code{FSETLOCKING_INTERNAL} or
  599. @code{FSETLOCKING_BYCALLER} depending on the state.
  600. @end vtable
  601. The return value of @code{__fsetlocking} is either
  602. @code{FSETLOCKING_INTERNAL} or @code{FSETLOCKING_BYCALLER} depending on
  603. the state of the stream before the call.
  604. This function and the values for the @var{type} parameter are declared
  605. in @file{stdio_ext.h}.
  606. @end deftypefun
  607. This function is especially useful when program code has to be used
  608. which is written without knowledge about the @code{_unlocked} functions
  609. (or if the programmer was too lazy to use them).
  610. @node Streams and I18N
  611. @section Streams in Internationalized Applications
  612. @w{ISO C90} introduced the new type @code{wchar_t} to allow handling
  613. larger character sets. What was missing was a possibility to output
  614. strings of @code{wchar_t} directly. One had to convert them into
  615. multibyte strings using @code{mbstowcs} (there was no @code{mbsrtowcs}
  616. yet) and then use the normal stream functions. While this is doable it
  617. is very cumbersome since performing the conversions is not trivial and
  618. greatly increases program complexity and size.
  619. The Unix standard early on (I think in XPG4.2) introduced two additional
  620. format specifiers for the @code{printf} and @code{scanf} families of
  621. functions. Printing and reading of single wide characters was made
  622. possible using the @code{%C} specifier and wide character strings can be
  623. handled with @code{%S}. These modifiers behave just like @code{%c} and
  624. @code{%s} only that they expect the corresponding argument to have the
  625. wide character type and that the wide character and string are
  626. transformed into/from multibyte strings before being used.
  627. This was a beginning but it is still not good enough. Not always is it
  628. desirable to use @code{printf} and @code{scanf}. The other, smaller and
  629. faster functions cannot handle wide characters. Second, it is not
  630. possible to have a format string for @code{printf} and @code{scanf}
  631. consisting of wide characters. The result is that format strings would
  632. have to be generated if they have to contain non-basic characters.
  633. @cindex C++ streams
  634. @cindex streams, C++
  635. In the @w{Amendment 1} to @w{ISO C90} a whole new set of functions was
  636. added to solve the problem. Most of the stream functions got a
  637. counterpart which take a wide character or wide character string instead
  638. of a character or string respectively. The new functions operate on the
  639. same streams (like @code{stdout}). This is different from the model of
  640. the C++ runtime library where separate streams for wide and normal I/O
  641. are used.
  642. @cindex orientation, stream
  643. @cindex stream orientation
  644. Being able to use the same stream for wide and normal operations comes
  645. with a restriction: a stream can be used either for wide operations or
  646. for normal operations. Once it is decided there is no way back. Only a
  647. call to @code{freopen} or @code{freopen64} can reset the
  648. @dfn{orientation}. The orientation can be decided in three ways:
  649. @itemize @bullet
  650. @item
  651. If any of the normal character functions are used (this includes the
  652. @code{fread} and @code{fwrite} functions) the stream is marked as not
  653. wide oriented.
  654. @item
  655. If any of the wide character functions are used the stream is marked as
  656. wide oriented.
  657. @item
  658. The @code{fwide} function can be used to set the orientation either way.
  659. @end itemize
  660. It is important to never mix the use of wide and not wide operations on
  661. a stream. There are no diagnostics issued. The application behavior
  662. will simply be strange or the application will simply crash. The
  663. @code{fwide} function can help avoid this.
  664. @deftypefun int fwide (FILE *@var{stream}, int @var{mode})
  665. @standards{ISO, wchar.h}
  666. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{}}}
  667. @c Querying is always safe, but changing the stream when it's in use
  668. @c upthread may be problematic. Like most lock-acquiring functions,
  669. @c this one may leak the lock if canceled.
  670. The @code{fwide} function can be used to set and query the state of the
  671. orientation of the stream @var{stream}. If the @var{mode} parameter has
  672. a positive value the streams get wide oriented, for negative values
  673. narrow oriented. It is not possible to overwrite previous orientations
  674. with @code{fwide}. I.e., if the stream @var{stream} was already
  675. oriented before the call nothing is done.
  676. If @var{mode} is zero the current orientation state is queried and
  677. nothing is changed.
  678. The @code{fwide} function returns a negative value, zero, or a positive
  679. value if the stream is narrow, not at all, or wide oriented
  680. respectively.
  681. This function was introduced in @w{Amendment 1} to @w{ISO C90} and is
  682. declared in @file{wchar.h}.
  683. @end deftypefun
  684. It is generally a good idea to orient a stream as early as possible.
  685. This can prevent surprise especially for the standard streams
  686. @code{stdin}, @code{stdout}, and @code{stderr}. If some library
  687. function in some situations uses one of these streams and this use
  688. orients the stream in a different way the rest of the application
  689. expects it one might end up with hard to reproduce errors. Remember
  690. that no errors are signal if the streams are used incorrectly. Leaving
  691. a stream unoriented after creation is normally only necessary for
  692. library functions which create streams which can be used in different
  693. contexts.
  694. When writing code which uses streams and which can be used in different
  695. contexts it is important to query the orientation of the stream before
  696. using it (unless the rules of the library interface demand a specific
  697. orientation). The following little, silly function illustrates this.
  698. @smallexample
  699. void
  700. print_f (FILE *fp)
  701. @{
  702. if (fwide (fp, 0) > 0)
  703. /* @r{Positive return value means wide orientation.} */
  704. fputwc (L'f', fp);
  705. else
  706. fputc ('f', fp);
  707. @}
  708. @end smallexample
  709. Note that in this case the function @code{print_f} decides about the
  710. orientation of the stream if it was unoriented before (will not happen
  711. if the advice above is followed).
  712. The encoding used for the @code{wchar_t} values is unspecified and the
  713. user must not make any assumptions about it. For I/O of @code{wchar_t}
  714. values this means that it is impossible to write these values directly
  715. to the stream. This is not what follows from the @w{ISO C} locale model
  716. either. What happens instead is that the bytes read from or written to
  717. the underlying media are first converted into the internal encoding
  718. chosen by the implementation for @code{wchar_t}. The external encoding
  719. is determined by the @code{LC_CTYPE} category of the current locale or
  720. by the @samp{ccs} part of the mode specification given to @code{fopen},
  721. @code{fopen64}, @code{freopen}, or @code{freopen64}. How and when the
  722. conversion happens is unspecified and it happens invisibly to the user.
  723. Since a stream is created in the unoriented state it has at that point
  724. no conversion associated with it. The conversion which will be used is
  725. determined by the @code{LC_CTYPE} category selected at the time the
  726. stream is oriented. If the locales are changed at the runtime this
  727. might produce surprising results unless one pays attention. This is
  728. just another good reason to orient the stream explicitly as soon as
  729. possible, perhaps with a call to @code{fwide}.
  730. @node Simple Output
  731. @section Simple Output by Characters or Lines
  732. @cindex writing to a stream, by characters
  733. This section describes functions for performing character- and
  734. line-oriented output.
  735. These narrow stream functions are declared in the header file
  736. @file{stdio.h} and the wide stream functions in @file{wchar.h}.
  737. @pindex stdio.h
  738. @pindex wchar.h
  739. @deftypefun int fputc (int @var{c}, FILE *@var{stream})
  740. @standards{ISO, stdio.h}
  741. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  742. @c If the stream is in use when interrupted by a signal, the recursive
  743. @c lock won't help ensure the stream is consistent; indeed, if fputc
  744. @c gets a signal precisely before the post-incremented _IO_write_ptr
  745. @c value is stored, we may overwrite the interrupted write. Conversely,
  746. @c depending on compiler optimizations, the incremented _IO_write_ptr
  747. @c may be stored before the character is stored in the buffer,
  748. @c corrupting the stream if async cancel hits between the two stores.
  749. @c There may be other reasons for AS- and AC-unsafety in the overflow
  750. @c cases.
  751. The @code{fputc} function converts the character @var{c} to type
  752. @code{unsigned char}, and writes it to the stream @var{stream}.
  753. @code{EOF} is returned if a write error occurs; otherwise the
  754. character @var{c} is returned.
  755. @end deftypefun
  756. @deftypefun wint_t fputwc (wchar_t @var{wc}, FILE *@var{stream})
  757. @standards{ISO, wchar.h}
  758. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  759. The @code{fputwc} function writes the wide character @var{wc} to the
  760. stream @var{stream}. @code{WEOF} is returned if a write error occurs;
  761. otherwise the character @var{wc} is returned.
  762. @end deftypefun
  763. @deftypefun int fputc_unlocked (int @var{c}, FILE *@var{stream})
  764. @standards{POSIX, stdio.h}
  765. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  766. @c The unlocked functions can't possibly satisfy the MT-Safety
  767. @c requirements on their own, because they require external locking for
  768. @c safety.
  769. The @code{fputc_unlocked} function is equivalent to the @code{fputc}
  770. function except that it does not implicitly lock the stream.
  771. @end deftypefun
  772. @deftypefun wint_t fputwc_unlocked (wchar_t @var{wc}, FILE *@var{stream})
  773. @standards{POSIX, wchar.h}
  774. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  775. The @code{fputwc_unlocked} function is equivalent to the @code{fputwc}
  776. function except that it does not implicitly lock the stream.
  777. This function is a GNU extension.
  778. @end deftypefun
  779. @deftypefun int putc (int @var{c}, FILE *@var{stream})
  780. @standards{ISO, stdio.h}
  781. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  782. This is just like @code{fputc}, except that it may be implemented as
  783. a macro and may evaluate the @var{stream} argument more than once.
  784. Therefore, @var{stream} should never be an expression with side-effects.
  785. @end deftypefun
  786. @deftypefun wint_t putwc (wchar_t @var{wc}, FILE *@var{stream})
  787. @standards{ISO, wchar.h}
  788. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  789. This is just like @code{fputwc}, except that it may be implemented as
  790. a macro and may evaluate the @var{stream} argument more than once.
  791. Therefore, @var{stream} should never be an expression with side-effects.
  792. @end deftypefun
  793. @deftypefun int putc_unlocked (int @var{c}, FILE *@var{stream})
  794. @standards{POSIX, stdio.h}
  795. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  796. The @code{putc_unlocked} function is equivalent to the @code{putc}
  797. function except that it does not implicitly lock the stream.
  798. Like @code{putc}, it may be implemented as a macro and may evaluate
  799. the @var{stream} argument more than once. Therefore, @var{stream}
  800. should not be an expression with side-effects.
  801. @end deftypefun
  802. @deftypefun wint_t putwc_unlocked (wchar_t @var{wc}, FILE *@var{stream})
  803. @standards{GNU, wchar.h}
  804. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  805. The @code{putwc_unlocked} function is equivalent to the @code{putwc}
  806. function except that it does not implicitly lock the stream.
  807. This function is a GNU extension.
  808. @end deftypefun
  809. @deftypefun int putchar (int @var{c})
  810. @standards{ISO, stdio.h}
  811. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  812. The @code{putchar} function is equivalent to @code{putc} with
  813. @code{stdout} as the value of the @var{stream} argument.
  814. @end deftypefun
  815. @deftypefun wint_t putwchar (wchar_t @var{wc})
  816. @standards{ISO, wchar.h}
  817. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  818. The @code{putwchar} function is equivalent to @code{putwc} with
  819. @code{stdout} as the value of the @var{stream} argument.
  820. @end deftypefun
  821. @deftypefun int putchar_unlocked (int @var{c})
  822. @standards{POSIX, stdio.h}
  823. @safety{@prelim{}@mtunsafe{@mtasurace{:stdout}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  824. The @code{putchar_unlocked} function is equivalent to the @code{putchar}
  825. function except that it does not implicitly lock the stream.
  826. @end deftypefun
  827. @deftypefun wint_t putwchar_unlocked (wchar_t @var{wc})
  828. @standards{GNU, wchar.h}
  829. @safety{@prelim{}@mtunsafe{@mtasurace{:stdout}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  830. The @code{putwchar_unlocked} function is equivalent to the @code{putwchar}
  831. function except that it does not implicitly lock the stream.
  832. This function is a GNU extension.
  833. @end deftypefun
  834. @deftypefun int fputs (const char *@var{s}, FILE *@var{stream})
  835. @standards{ISO, stdio.h}
  836. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  837. The function @code{fputs} writes the string @var{s} to the stream
  838. @var{stream}. The terminating null character is not written.
  839. This function does @emph{not} add a newline character, either.
  840. It outputs only the characters in the string.
  841. This function returns @code{EOF} if a write error occurs, and otherwise
  842. a non-negative value.
  843. For example:
  844. @smallexample
  845. fputs ("Are ", stdout);
  846. fputs ("you ", stdout);
  847. fputs ("hungry?\n", stdout);
  848. @end smallexample
  849. @noindent
  850. outputs the text @samp{Are you hungry?} followed by a newline.
  851. @end deftypefun
  852. @deftypefun int fputws (const wchar_t *@var{ws}, FILE *@var{stream})
  853. @standards{ISO, wchar.h}
  854. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
  855. The function @code{fputws} writes the wide character string @var{ws} to
  856. the stream @var{stream}. The terminating null character is not written.
  857. This function does @emph{not} add a newline character, either. It
  858. outputs only the characters in the string.
  859. This function returns @code{WEOF} if a write error occurs, and otherwise
  860. a non-negative value.
  861. @end deftypefun
  862. @deftypefun int fputs_unlocked (const char *@var{s}, FILE *@var{stream})
  863. @standards{GNU, stdio.h}
  864. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  865. The @code{fputs_unlocked} function is equivalent to the @code{fputs}
  866. function except that it does not implicitly lock the stream.
  867. This function is a GNU extension.
  868. @end deftypefun
  869. @deftypefun int fputws_unlocked (const wchar_t *@var{ws}, FILE *@var{stream})
  870. @standards{GNU, wchar.h}
  871. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  872. The @code{fputws_unlocked} function is equivalent to the @code{fputws}
  873. function except that it does not implicitly lock the stream.
  874. This function is a GNU extension.
  875. @end deftypefun
  876. @deftypefun int puts (const char *@var{s})
  877. @standards{ISO, stdio.h}
  878. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  879. The @code{puts} function writes the string @var{s} to the stream
  880. @code{stdout} followed by a newline. The terminating null character of
  881. the string is not written. (Note that @code{fputs} does @emph{not}
  882. write a newline as this function does.)
  883. @code{puts} is the most convenient function for printing simple
  884. messages. For example:
  885. @smallexample
  886. puts ("This is a message.");
  887. @end smallexample
  888. @noindent
  889. outputs the text @samp{This is a message.} followed by a newline.
  890. @end deftypefun
  891. @deftypefun int putw (int @var{w}, FILE *@var{stream})
  892. @standards{SVID, stdio.h}
  893. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  894. This function writes the word @var{w} (that is, an @code{int}) to
  895. @var{stream}. It is provided for compatibility with SVID, but we
  896. recommend you use @code{fwrite} instead (@pxref{Block Input/Output}).
  897. @end deftypefun
  898. @node Character Input
  899. @section Character Input
  900. @cindex reading from a stream, by characters
  901. This section describes functions for performing character-oriented
  902. input. These narrow stream functions are declared in the header file
  903. @file{stdio.h} and the wide character functions are declared in
  904. @file{wchar.h}.
  905. @pindex stdio.h
  906. @pindex wchar.h
  907. These functions return an @code{int} or @code{wint_t} value (for narrow
  908. and wide stream functions respectively) that is either a character of
  909. input, or the special value @code{EOF}/@code{WEOF} (usually -1). For
  910. the narrow stream functions it is important to store the result of these
  911. functions in a variable of type @code{int} instead of @code{char}, even
  912. when you plan to use it only as a character. Storing @code{EOF} in a
  913. @code{char} variable truncates its value to the size of a character, so
  914. that it is no longer distinguishable from the valid character
  915. @samp{(char) -1}. So always use an @code{int} for the result of
  916. @code{getc} and friends, and check for @code{EOF} after the call; once
  917. you've verified that the result is not @code{EOF}, you can be sure that
  918. it will fit in a @samp{char} variable without loss of information.
  919. @deftypefun int fgetc (FILE *@var{stream})
  920. @standards{ISO, stdio.h}
  921. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  922. @c Same caveats as fputc, but instead of losing a write in case of async
  923. @c signals, we may read the same character more than once, and the
  924. @c stream may be left in odd states due to cancellation in the underflow
  925. @c cases.
  926. This function reads the next character as an @code{unsigned char} from
  927. the stream @var{stream} and returns its value, converted to an
  928. @code{int}. If an end-of-file condition or read error occurs,
  929. @code{EOF} is returned instead.
  930. @end deftypefun
  931. @deftypefun wint_t fgetwc (FILE *@var{stream})
  932. @standards{ISO, wchar.h}
  933. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  934. This function reads the next wide character from the stream @var{stream}
  935. and returns its value. If an end-of-file condition or read error
  936. occurs, @code{WEOF} is returned instead.
  937. @end deftypefun
  938. @deftypefun int fgetc_unlocked (FILE *@var{stream})
  939. @standards{POSIX, stdio.h}
  940. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  941. The @code{fgetc_unlocked} function is equivalent to the @code{fgetc}
  942. function except that it does not implicitly lock the stream.
  943. @end deftypefun
  944. @deftypefun wint_t fgetwc_unlocked (FILE *@var{stream})
  945. @standards{GNU, wchar.h}
  946. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  947. The @code{fgetwc_unlocked} function is equivalent to the @code{fgetwc}
  948. function except that it does not implicitly lock the stream.
  949. This function is a GNU extension.
  950. @end deftypefun
  951. @deftypefun int getc (FILE *@var{stream})
  952. @standards{ISO, stdio.h}
  953. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  954. This is just like @code{fgetc}, except that it may be implemented as
  955. a macro and may evaluate the @var{stream} argument more than once.
  956. Therefore, @var{stream} should never be an expression with side-effects.
  957. @end deftypefun
  958. @deftypefun wint_t getwc (FILE *@var{stream})
  959. @standards{ISO, wchar.h}
  960. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  961. This is just like @code{fgetwc}, except that it may be implemented as
  962. a macro and may evaluate the @var{stream} argument more than once.
  963. Therefore, @var{stream} should never be an expression with side-effects.
  964. @end deftypefun
  965. @deftypefun int getc_unlocked (FILE *@var{stream})
  966. @standards{POSIX, stdio.h}
  967. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  968. The @code{getc_unlocked} function is equivalent to the @code{getc}
  969. function except that it does not implicitly lock the stream.
  970. Like @code{getc}, it may be implemented as a macro and may evaluate
  971. the @var{stream} argument more than once. Therefore, @var{stream}
  972. should not be an expression with side-effects.
  973. @end deftypefun
  974. @deftypefun wint_t getwc_unlocked (FILE *@var{stream})
  975. @standards{GNU, wchar.h}
  976. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  977. The @code{getwc_unlocked} function is equivalent to the @code{getwc}
  978. function except that it does not implicitly lock the stream.
  979. This function is a GNU extension.
  980. @end deftypefun
  981. @deftypefun int getchar (void)
  982. @standards{ISO, stdio.h}
  983. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  984. The @code{getchar} function is equivalent to @code{getc} with @code{stdin}
  985. as the value of the @var{stream} argument.
  986. @end deftypefun
  987. @deftypefun wint_t getwchar (void)
  988. @standards{ISO, wchar.h}
  989. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  990. The @code{getwchar} function is equivalent to @code{getwc} with @code{stdin}
  991. as the value of the @var{stream} argument.
  992. @end deftypefun
  993. @deftypefun int getchar_unlocked (void)
  994. @standards{POSIX, stdio.h}
  995. @safety{@prelim{}@mtunsafe{@mtasurace{:stdin}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  996. The @code{getchar_unlocked} function is equivalent to the @code{getchar}
  997. function except that it does not implicitly lock the stream.
  998. @end deftypefun
  999. @deftypefun wint_t getwchar_unlocked (void)
  1000. @standards{GNU, wchar.h}
  1001. @safety{@prelim{}@mtunsafe{@mtasurace{:stdin}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  1002. The @code{getwchar_unlocked} function is equivalent to the @code{getwchar}
  1003. function except that it does not implicitly lock the stream.
  1004. This function is a GNU extension.
  1005. @end deftypefun
  1006. Here is an example of a function that does input using @code{fgetc}. It
  1007. would work just as well using @code{getc} instead, or using
  1008. @code{getchar ()} instead of @w{@code{fgetc (stdin)}}. The code would
  1009. also work the same for the wide character stream functions.
  1010. @smallexample
  1011. int
  1012. y_or_n_p (const char *question)
  1013. @{
  1014. fputs (question, stdout);
  1015. while (1)
  1016. @{
  1017. int c, answer;
  1018. /* @r{Write a space to separate answer from question.} */
  1019. fputc (' ', stdout);
  1020. /* @r{Read the first character of the line.}
  1021. @r{This should be the answer character, but might not be.} */
  1022. c = tolower (fgetc (stdin));
  1023. answer = c;
  1024. /* @r{Discard rest of input line.} */
  1025. while (c != '\n' && c != EOF)
  1026. c = fgetc (stdin);
  1027. /* @r{Obey the answer if it was valid.} */
  1028. if (answer == 'y')
  1029. return 1;
  1030. if (answer == 'n')
  1031. return 0;
  1032. /* @r{Answer was invalid: ask for valid answer.} */
  1033. fputs ("Please answer y or n:", stdout);
  1034. @}
  1035. @}
  1036. @end smallexample
  1037. @deftypefun int getw (FILE *@var{stream})
  1038. @standards{SVID, stdio.h}
  1039. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1040. This function reads a word (that is, an @code{int}) from @var{stream}.
  1041. It's provided for compatibility with SVID. We recommend you use
  1042. @code{fread} instead (@pxref{Block Input/Output}). Unlike @code{getc},
  1043. any @code{int} value could be a valid result. @code{getw} returns
  1044. @code{EOF} when it encounters end-of-file or an error, but there is no
  1045. way to distinguish this from an input word with value -1.
  1046. @end deftypefun
  1047. @node Line Input
  1048. @section Line-Oriented Input
  1049. Since many programs interpret input on the basis of lines, it is
  1050. convenient to have functions to read a line of text from a stream.
  1051. Standard C has functions to do this, but they aren't very safe: null
  1052. characters and even (for @code{gets}) long lines can confuse them. So
  1053. @theglibc{} provides the @code{getline} function that makes it easy to
  1054. read lines reliably.
  1055. The @code{getdelim} function is a generalized version of @code{getline}.
  1056. It reads a delimited record, defined as everything through the next
  1057. occurrence of a specified delimiter character. These functions were
  1058. both GNU extensions until standardized by POSIX.1-2008.
  1059. All these functions are declared in @file{stdio.h}.
  1060. @deftypefun ssize_t getline (char **restrict @var{lineptr}, size_t *restrict @var{n}, FILE *restrict @var{stream})
  1061. @standards{POSIX.1-2008, stdio.h}
  1062. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@aculock{} @acucorrupt{} @acsmem{}}}
  1063. @c Besides the usual possibility of getting an inconsistent stream in a
  1064. @c signal handler or leaving it inconsistent in case of cancellation,
  1065. @c the possibility of leaving a dangling pointer upon cancellation
  1066. @c between reallocing the buffer at *lineptr and updating the pointer
  1067. @c brings about another case of @acucorrupt.
  1068. This function reads an entire line from @var{stream}, storing the text
  1069. (including the newline and a terminating null character) in a buffer
  1070. and storing the buffer address in @code{*@var{lineptr}}.
  1071. Before calling @code{getline}, you should place in @code{*@var{lineptr}}
  1072. the address of a buffer @code{*@var{n}} bytes long, allocated with
  1073. @code{malloc}. If this buffer is long enough to hold the line,
  1074. @code{getline} stores the line in this buffer. Otherwise,
  1075. @code{getline} makes the buffer bigger using @code{realloc}, storing the
  1076. new buffer address back in @code{*@var{lineptr}} and the increased size
  1077. back in @code{*@var{n}}.
  1078. @xref{Unconstrained Allocation}.
  1079. If you set @code{*@var{lineptr}} to a null pointer, and @code{*@var{n}}
  1080. to zero, before the call, then @code{getline} allocates the initial
  1081. buffer for you by calling @code{malloc}. This buffer remains allocated
  1082. even if @code{getline} encounters errors and is unable to read any bytes.
  1083. In either case, when @code{getline} returns, @code{*@var{lineptr}} is
  1084. a @code{char *} which points to the text of the line.
  1085. When @code{getline} is successful, it returns the number of characters
  1086. read (including the newline, but not including the terminating null).
  1087. This value enables you to distinguish null characters that are part of
  1088. the line from the null character inserted as a terminator.
  1089. This function was originally a GNU extension, but was added in
  1090. POSIX.1-2008.
  1091. If an error occurs or end of file is reached without any bytes read,
  1092. @code{getline} returns @code{-1}. POSIX leaves the contents of
  1093. @code{*@var{lineptr}} undefined when @code{getline} returns @code{-1}.
  1094. If the @glibcadj{} implementation of @code{getline} allocates the
  1095. initial buffer it will null terminate it to prevent the caller from
  1096. reading uninitialized memory if no characters can be read from
  1097. @code{stream}.
  1098. @end deftypefun
  1099. @deftypefun ssize_t getdelim (char **restrict @var{lineptr}, size_t *restrict @var{n}, int @var{delimiter}, FILE *restrict @var{stream})
  1100. @standards{POSIX.1-2008, stdio.h}
  1101. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@aculock{} @acucorrupt{} @acsmem{}}}
  1102. @c See the getline @acucorrupt note.
  1103. This function is like @code{getline} except that the character which
  1104. tells it to stop reading is not necessarily newline. The argument
  1105. @var{delimiter} specifies the delimiter character; @code{getdelim} keeps
  1106. reading until it sees that character (or end of file).
  1107. The text is stored in @var{lineptr}, including the delimiter character
  1108. and a terminating null. Like @code{getline}, @code{getdelim} makes
  1109. @var{lineptr} bigger if it isn't big enough.
  1110. This function was originally a GNU extension, but was added in
  1111. POSIX.1-2008.
  1112. @code{getline} is in fact implemented in terms of @code{getdelim}, just
  1113. like this:
  1114. @smallexample
  1115. ssize_t
  1116. getline (char **lineptr, size_t *n, FILE *stream)
  1117. @{
  1118. return getdelim (lineptr, n, '\n', stream);
  1119. @}
  1120. @end smallexample
  1121. @end deftypefun
  1122. @deftypefun {char *} fgets (char *@var{s}, int @var{count}, FILE *@var{stream})
  1123. @standards{ISO, stdio.h}
  1124. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1125. The @code{fgets} function reads characters from the stream @var{stream}
  1126. up to and including a newline character and stores them in the string
  1127. @var{s}, adding a null character to mark the end of the string. You
  1128. must supply @var{count} characters worth of space in @var{s}, but the
  1129. number of characters read is at most @var{count} @minus{} 1. The extra
  1130. character space is used to hold the null character at the end of the
  1131. string.
  1132. If the system is already at end of file when you call @code{fgets}, then
  1133. the contents of the array @var{s} are unchanged and a null pointer is
  1134. returned. A null pointer is also returned if a read error occurs.
  1135. Otherwise, the return value is the pointer @var{s}.
  1136. @strong{Warning:} If the input data has a null character, you can't tell.
  1137. So don't use @code{fgets} unless you know the data cannot contain a null.
  1138. Don't use it to read files edited by the user because, if the user inserts
  1139. a null character, you should either handle it properly or print a clear
  1140. error message. We recommend using @code{getline} instead of @code{fgets}.
  1141. @end deftypefun
  1142. @deftypefun {wchar_t *} fgetws (wchar_t *@var{ws}, int @var{count}, FILE *@var{stream})
  1143. @standards{ISO, wchar.h}
  1144. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1145. The @code{fgetws} function reads wide characters from the stream
  1146. @var{stream} up to and including a newline character and stores them in
  1147. the string @var{ws}, adding a null wide character to mark the end of the
  1148. string. You must supply @var{count} wide characters worth of space in
  1149. @var{ws}, but the number of characters read is at most @var{count}
  1150. @minus{} 1. The extra character space is used to hold the null wide
  1151. character at the end of the string.
  1152. If the system is already at end of file when you call @code{fgetws}, then
  1153. the contents of the array @var{ws} are unchanged and a null pointer is
  1154. returned. A null pointer is also returned if a read error occurs.
  1155. Otherwise, the return value is the pointer @var{ws}.
  1156. @strong{Warning:} If the input data has a null wide character (which are
  1157. null bytes in the input stream), you can't tell. So don't use
  1158. @code{fgetws} unless you know the data cannot contain a null. Don't use
  1159. it to read files edited by the user because, if the user inserts a null
  1160. character, you should either handle it properly or print a clear error
  1161. message.
  1162. @comment XXX We need getwline!!!
  1163. @end deftypefun
  1164. @deftypefun {char *} fgets_unlocked (char *@var{s}, int @var{count}, FILE *@var{stream})
  1165. @standards{GNU, stdio.h}
  1166. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  1167. The @code{fgets_unlocked} function is equivalent to the @code{fgets}
  1168. function except that it does not implicitly lock the stream.
  1169. This function is a GNU extension.
  1170. @end deftypefun
  1171. @deftypefun {wchar_t *} fgetws_unlocked (wchar_t *@var{ws}, int @var{count}, FILE *@var{stream})
  1172. @standards{GNU, wchar.h}
  1173. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  1174. The @code{fgetws_unlocked} function is equivalent to the @code{fgetws}
  1175. function except that it does not implicitly lock the stream.
  1176. This function is a GNU extension.
  1177. @end deftypefun
  1178. @deftypefn {Deprecated function} {char *} gets (char *@var{s})
  1179. @standards{ISO, stdio.h}
  1180. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1181. The function @code{gets} reads characters from the stream @code{stdin}
  1182. up to the next newline character, and stores them in the string @var{s}.
  1183. The newline character is discarded (note that this differs from the
  1184. behavior of @code{fgets}, which copies the newline character into the
  1185. string). If @code{gets} encounters a read error or end-of-file, it
  1186. returns a null pointer; otherwise it returns @var{s}.
  1187. @strong{Warning:} The @code{gets} function is @strong{very dangerous}
  1188. because it provides no protection against overflowing the string
  1189. @var{s}. @Theglibc{} includes it for compatibility only. You
  1190. should @strong{always} use @code{fgets} or @code{getline} instead. To
  1191. remind you of this, the linker (if using GNU @code{ld}) will issue a
  1192. warning whenever you use @code{gets}.
  1193. @end deftypefn
  1194. @node Unreading
  1195. @section Unreading
  1196. @cindex peeking at input
  1197. @cindex unreading characters
  1198. @cindex pushing input back
  1199. In parser programs it is often useful to examine the next character in
  1200. the input stream without removing it from the stream. This is called
  1201. ``peeking ahead'' at the input because your program gets a glimpse of
  1202. the input it will read next.
  1203. Using stream I/O, you can peek ahead at input by first reading it and
  1204. then @dfn{unreading} it (also called @dfn{pushing it back} on the stream).
  1205. Unreading a character makes it available to be input again from the stream,
  1206. by the next call to @code{fgetc} or other input function on that stream.
  1207. @menu
  1208. * Unreading Idea:: An explanation of unreading with pictures.
  1209. * How Unread:: How to call @code{ungetc} to do unreading.
  1210. @end menu
  1211. @node Unreading Idea
  1212. @subsection What Unreading Means
  1213. Here is a pictorial explanation of unreading. Suppose you have a
  1214. stream reading a file that contains just six characters, the letters
  1215. @samp{foobar}. Suppose you have read three characters so far. The
  1216. situation looks like this:
  1217. @smallexample
  1218. f o o b a r
  1219. ^
  1220. @end smallexample
  1221. @noindent
  1222. so the next input character will be @samp{b}.
  1223. @c @group Invalid outside @example
  1224. If instead of reading @samp{b} you unread the letter @samp{o}, you get a
  1225. situation like this:
  1226. @smallexample
  1227. f o o b a r
  1228. |
  1229. o--
  1230. ^
  1231. @end smallexample
  1232. @noindent
  1233. so that the next input characters will be @samp{o} and @samp{b}.
  1234. @c @end group
  1235. @c @group
  1236. If you unread @samp{9} instead of @samp{o}, you get this situation:
  1237. @smallexample
  1238. f o o b a r
  1239. |
  1240. 9--
  1241. ^
  1242. @end smallexample
  1243. @noindent
  1244. so that the next input characters will be @samp{9} and @samp{b}.
  1245. @c @end group
  1246. @node How Unread
  1247. @subsection Using @code{ungetc} To Do Unreading
  1248. The function to unread a character is called @code{ungetc}, because it
  1249. reverses the action of @code{getc}.
  1250. @deftypefun int ungetc (int @var{c}, FILE *@var{stream})
  1251. @standards{ISO, stdio.h}
  1252. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1253. The @code{ungetc} function pushes back the character @var{c} onto the
  1254. input stream @var{stream}. So the next input from @var{stream} will
  1255. read @var{c} before anything else.
  1256. If @var{c} is @code{EOF}, @code{ungetc} does nothing and just returns
  1257. @code{EOF}. This lets you call @code{ungetc} with the return value of
  1258. @code{getc} without needing to check for an error from @code{getc}.
  1259. The character that you push back doesn't have to be the same as the last
  1260. character that was actually read from the stream. In fact, it isn't
  1261. necessary to actually read any characters from the stream before
  1262. unreading them with @code{ungetc}! But that is a strange way to write a
  1263. program; usually @code{ungetc} is used only to unread a character that
  1264. was just read from the same stream. @Theglibc{} supports this
  1265. even on files opened in binary mode, but other systems might not.
  1266. @Theglibc{} supports pushing back multiple characters; subsequently
  1267. reading from the stream retrieves the characters in the reverse order
  1268. that they were pushed.
  1269. Pushing back characters doesn't alter the file; only the internal
  1270. buffering for the stream is affected. If a file positioning function
  1271. (such as @code{fseek}, @code{fseeko} or @code{rewind}; @pxref{File
  1272. Positioning}) is called, any pending pushed-back characters are
  1273. discarded.
  1274. Unreading a character on a stream that is at end of file clears the
  1275. end-of-file indicator for the stream, because it makes the character of
  1276. input available. After you read that character, trying to read again
  1277. will encounter end of file.
  1278. @end deftypefun
  1279. @deftypefun wint_t ungetwc (wint_t @var{wc}, FILE *@var{stream})
  1280. @standards{ISO, wchar.h}
  1281. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1282. The @code{ungetwc} function behaves just like @code{ungetc} just that it
  1283. pushes back a wide character.
  1284. @end deftypefun
  1285. Here is an example showing the use of @code{getc} and @code{ungetc} to
  1286. skip over whitespace characters. When this function reaches a
  1287. non-whitespace character, it unreads that character to be seen again on
  1288. the next read operation on the stream.
  1289. @smallexample
  1290. #include <stdio.h>
  1291. #include <ctype.h>
  1292. void
  1293. skip_whitespace (FILE *stream)
  1294. @{
  1295. int c;
  1296. do
  1297. /* @r{No need to check for @code{EOF} because it is not}
  1298. @r{@code{isspace}, and @code{ungetc} ignores @code{EOF}.} */
  1299. c = getc (stream);
  1300. while (isspace (c));
  1301. ungetc (c, stream);
  1302. @}
  1303. @end smallexample
  1304. @node Block Input/Output
  1305. @section Block Input/Output
  1306. This section describes how to do input and output operations on blocks
  1307. of data. You can use these functions to read and write binary data, as
  1308. well as to read and write text in fixed-size blocks instead of by
  1309. characters or lines.
  1310. @cindex binary I/O to a stream
  1311. @cindex block I/O to a stream
  1312. @cindex reading from a stream, by blocks
  1313. @cindex writing to a stream, by blocks
  1314. Binary files are typically used to read and write blocks of data in the
  1315. same format as is used to represent the data in a running program. In
  1316. other words, arbitrary blocks of memory---not just character or string
  1317. objects---can be written to a binary file, and meaningfully read in
  1318. again by the same program.
  1319. Storing data in binary form is often considerably more efficient than
  1320. using the formatted I/O functions. Also, for floating-point numbers,
  1321. the binary form avoids possible loss of precision in the conversion
  1322. process. On the other hand, binary files can't be examined or modified
  1323. easily using many standard file utilities (such as text editors), and
  1324. are not portable between different implementations of the language, or
  1325. different kinds of computers.
  1326. These functions are declared in @file{stdio.h}.
  1327. @pindex stdio.h
  1328. @deftypefun size_t fread (void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
  1329. @standards{ISO, stdio.h}
  1330. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1331. This function reads up to @var{count} objects of size @var{size} into
  1332. the array @var{data}, from the stream @var{stream}. It returns the
  1333. number of objects actually read, which might be less than @var{count} if
  1334. a read error occurs or the end of the file is reached. This function
  1335. returns a value of zero (and doesn't read anything) if either @var{size}
  1336. or @var{count} is zero.
  1337. If @code{fread} encounters end of file in the middle of an object, it
  1338. returns the number of complete objects read, and discards the partial
  1339. object. Therefore, the stream remains at the actual end of the file.
  1340. @end deftypefun
  1341. @deftypefun size_t fread_unlocked (void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
  1342. @standards{GNU, stdio.h}
  1343. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  1344. The @code{fread_unlocked} function is equivalent to the @code{fread}
  1345. function except that it does not implicitly lock the stream.
  1346. This function is a GNU extension.
  1347. This function may be implemented as a macro and may evaluate
  1348. @var{stream} more than once. Therefore, @var{stream} should not be an
  1349. expression with side-effects.
  1350. @end deftypefun
  1351. @deftypefun size_t fwrite (const void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
  1352. @standards{ISO, stdio.h}
  1353. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  1354. This function writes up to @var{count} objects of size @var{size} from
  1355. the array @var{data}, to the stream @var{stream}. The return value is
  1356. normally @var{count}, if the call succeeds. Any other value indicates
  1357. some sort of error, such as running out of space.
  1358. @end deftypefun
  1359. @deftypefun size_t fwrite_unlocked (const void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
  1360. @standards{GNU, stdio.h}
  1361. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  1362. The @code{fwrite_unlocked} function is equivalent to the @code{fwrite}
  1363. function except that it does not implicitly lock the stream.
  1364. This function is a GNU extension.
  1365. This function may be implemented as a macro and may evaluate
  1366. @var{stream} more than once. Therefore, @var{stream} should not be an
  1367. expression with side-effects.
  1368. @end deftypefun
  1369. @node Formatted Output
  1370. @section Formatted Output
  1371. @cindex format string, for @code{printf}
  1372. @cindex template, for @code{printf}
  1373. @cindex formatted output to a stream
  1374. @cindex writing to a stream, formatted
  1375. The functions described in this section (@code{printf} and related
  1376. functions) provide a convenient way to perform formatted output. You
  1377. call @code{printf} with a @dfn{format string} or @dfn{template string}
  1378. that specifies how to format the values of the remaining arguments.
  1379. Unless your program is a filter that specifically performs line- or
  1380. character-oriented processing, using @code{printf} or one of the other
  1381. related functions described in this section is usually the easiest and
  1382. most concise way to perform output. These functions are especially
  1383. useful for printing error messages, tables of data, and the like.
  1384. @menu
  1385. * Formatted Output Basics:: Some examples to get you started.
  1386. * Output Conversion Syntax:: General syntax of conversion
  1387. specifications.
  1388. * Table of Output Conversions:: Summary of output conversions and
  1389. what they do.
  1390. * Integer Conversions:: Details about formatting of integers.
  1391. * Floating-Point Conversions:: Details about formatting of
  1392. floating-point numbers.
  1393. * Other Output Conversions:: Details about formatting of strings,
  1394. characters, pointers, and the like.
  1395. * Formatted Output Functions:: Descriptions of the actual functions.
  1396. * Dynamic Output:: Functions that allocate memory for the output.
  1397. * Variable Arguments Output:: @code{vprintf} and friends.
  1398. * Parsing a Template String:: What kinds of args does a given template
  1399. call for?
  1400. * Example of Parsing:: Sample program using @code{parse_printf_format}.
  1401. @end menu
  1402. @node Formatted Output Basics
  1403. @subsection Formatted Output Basics
  1404. The @code{printf} function can be used to print any number of arguments.
  1405. The template string argument you supply in a call provides
  1406. information not only about the number of additional arguments, but also
  1407. about their types and what style should be used for printing them.
  1408. Ordinary characters in the template string are simply written to the
  1409. output stream as-is, while @dfn{conversion specifications} introduced by
  1410. a @samp{%} character in the template cause subsequent arguments to be
  1411. formatted and written to the output stream. For example,
  1412. @cindex conversion specifications (@code{printf})
  1413. @smallexample
  1414. int pct = 37;
  1415. char filename[] = "foo.txt";
  1416. printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
  1417. filename, pct);
  1418. @end smallexample
  1419. @noindent
  1420. produces output like
  1421. @smallexample
  1422. Processing of `foo.txt' is 37% finished.
  1423. Please be patient.
  1424. @end smallexample
  1425. This example shows the use of the @samp{%d} conversion to specify that
  1426. an @code{int} argument should be printed in decimal notation, the
  1427. @samp{%s} conversion to specify printing of a string argument, and
  1428. the @samp{%%} conversion to print a literal @samp{%} character.
  1429. There are also conversions for printing an integer argument as an
  1430. unsigned value in binary, octal, decimal, or hexadecimal radix
  1431. (@samp{%b}, @samp{%o}, @samp{%u}, or @samp{%x}, respectively); or as a
  1432. character value (@samp{%c}).
  1433. Floating-point numbers can be printed in normal, fixed-point notation
  1434. using the @samp{%f} conversion or in exponential notation using the
  1435. @samp{%e} conversion. The @samp{%g} conversion uses either @samp{%e}
  1436. or @samp{%f} format, depending on what is more appropriate for the
  1437. magnitude of the particular number.
  1438. You can control formatting more precisely by writing @dfn{modifiers}
  1439. between the @samp{%} and the character that indicates which conversion
  1440. to apply. These slightly alter the ordinary behavior of the conversion.
  1441. For example, most conversion specifications permit you to specify a
  1442. minimum field width and a flag indicating whether you want the result
  1443. left- or right-justified within the field.
  1444. The specific flags and modifiers that are permitted and their
  1445. interpretation vary depending on the particular conversion. They're all
  1446. described in more detail in the following sections. Don't worry if this
  1447. all seems excessively complicated at first; you can almost always get
  1448. reasonable free-format output without using any of the modifiers at all.
  1449. The modifiers are mostly used to make the output look ``prettier'' in
  1450. tables.
  1451. @node Output Conversion Syntax
  1452. @subsection Output Conversion Syntax
  1453. This section provides details about the precise syntax of conversion
  1454. specifications that can appear in a @code{printf} template
  1455. string.
  1456. Characters in the template string that are not part of a conversion
  1457. specification are printed as-is to the output stream. Multibyte
  1458. character sequences (@pxref{Character Set Handling}) are permitted in a
  1459. template string.
  1460. The conversion specifications in a @code{printf} template string have
  1461. the general form:
  1462. @smallexample
  1463. % @r{[} @var{param-no} @r{$]} @var{flags} @var{width} @r{[} . @var{precision} @r{]} @var{type} @var{conversion}
  1464. @end smallexample
  1465. @noindent
  1466. or
  1467. @smallexample
  1468. % @r{[} @var{param-no} @r{$]} @var{flags} @var{width} . @r{*} @r{[} @var{param-no} @r{$]} @var{type} @var{conversion}
  1469. @end smallexample
  1470. For example, in the conversion specifier @samp{%-10.8ld}, the @samp{-}
  1471. is a flag, @samp{10} specifies the field width, the precision is
  1472. @samp{8}, the letter @samp{l} is a type modifier, and @samp{d} specifies
  1473. the conversion style. (This particular type specifier says to
  1474. print a @code{long int} argument in decimal notation, with a minimum of
  1475. 8 digits left-justified in a field at least 10 characters wide.)
  1476. In more detail, output conversion specifications consist of an
  1477. initial @samp{%} character followed in sequence by:
  1478. @itemize @bullet
  1479. @item
  1480. An optional specification of the parameter used for this format.
  1481. Normally the parameters to the @code{printf} function are assigned to the
  1482. formats in the order of appearance in the format string. But in some
  1483. situations (such as message translation) this is not desirable and this
  1484. extension allows an explicit parameter to be specified.
  1485. The @var{param-no} parts of the format must be integers in the range of
  1486. 1 to the maximum number of arguments present to the function call. Some
  1487. implementations limit this number to a certain upper bound. The exact
  1488. limit can be retrieved by the following constant.
  1489. @defvr Macro NL_ARGMAX
  1490. The value of @code{NL_ARGMAX} is the maximum value allowed for the
  1491. specification of a positional parameter in a @code{printf} call. The
  1492. actual value in effect at runtime can be retrieved by using
  1493. @code{sysconf} using the @code{_SC_NL_ARGMAX} parameter @pxref{Sysconf
  1494. Definition}.
  1495. Some systems have a quite low limit such as @math{9} for @w{System V}
  1496. systems. @Theglibc{} has no real limit.
  1497. @end defvr
  1498. If any of the formats has a specification for the parameter position all
  1499. of them in the format string shall have one. Otherwise the behavior is
  1500. undefined.
  1501. @item
  1502. Zero or more @dfn{flag characters} that modify the normal behavior of
  1503. the conversion specification.
  1504. @cindex flag character (@code{printf})
  1505. @item
  1506. An optional decimal integer specifying the @dfn{minimum field width}.
  1507. If the normal conversion produces fewer characters than this, the field
  1508. is padded with spaces to the specified width. This is a @emph{minimum}
  1509. value; if the normal conversion produces more characters than this, the
  1510. field is @emph{not} truncated. Normally, the output is right-justified
  1511. within the field.
  1512. @cindex minimum field width (@code{printf})
  1513. You can also specify a field width of @samp{*}. This means that the
  1514. next argument in the argument list (before the actual value to be
  1515. printed) is used as the field width. The value must be an @code{int}.
  1516. If the value is negative, this means to set the @samp{-} flag (see
  1517. below) and to use the absolute value as the field width.
  1518. @item
  1519. An optional @dfn{precision} to specify the number of digits to be
  1520. written for the numeric conversions. If the precision is specified, it
  1521. consists of a period (@samp{.}) followed optionally by a decimal integer
  1522. (which defaults to zero if omitted).
  1523. @cindex precision (@code{printf})
  1524. You can also specify a precision of @samp{*}. This means that the next
  1525. argument in the argument list (before the actual value to be printed) is
  1526. used as the precision. The value must be an @code{int}, and is ignored
  1527. if it is negative. If you specify @samp{*} for both the field width and
  1528. precision, the field width argument precedes the precision argument.
  1529. Other C library versions may not recognize this syntax.
  1530. @item
  1531. An optional @dfn{type modifier character}, which is used to specify the
  1532. data type of the corresponding argument if it differs from the default
  1533. type. (For example, the integer conversions assume a type of @code{int},
  1534. but you can specify @samp{h}, @samp{l}, or @samp{L} for other integer
  1535. types.)
  1536. @cindex type modifier character (@code{printf})
  1537. @item
  1538. A character that specifies the conversion to be applied.
  1539. @end itemize
  1540. The exact options that are permitted and how they are interpreted vary
  1541. between the different conversion specifiers. See the descriptions of the
  1542. individual conversions for information about the particular options that
  1543. they use.
  1544. With the @samp{-Wformat} option, the GNU C compiler checks calls to
  1545. @code{printf} and related functions. It examines the format string and
  1546. verifies that the correct number and types of arguments are supplied.
  1547. There is also a GNU C syntax to tell the compiler that a function you
  1548. write uses a @code{printf}-style format string.
  1549. @xref{Function Attributes, , Declaring Attributes of Functions,
  1550. gcc, Using GNU CC}, for more information.
  1551. @node Table of Output Conversions
  1552. @subsection Table of Output Conversions
  1553. @cindex output conversions, for @code{printf}
  1554. Here is a table summarizing what all the different conversions do:
  1555. @table @asis
  1556. @item @samp{%d}, @samp{%i}
  1557. Print an integer as a signed decimal number. @xref{Integer
  1558. Conversions}, for details. @samp{%d} and @samp{%i} are synonymous for
  1559. output, but are different when used with @code{scanf} for input
  1560. (@pxref{Table of Input Conversions}).
  1561. @item @samp{%b}, @samp{%B}
  1562. Print an integer as an unsigned binary number. @samp{%b} uses
  1563. lower-case @samp{b} with the @samp{#} flag and @samp{%B} uses
  1564. upper-case. @samp{%b} is an ISO C23 feature; @samp{%B} is an
  1565. optional ISO C23 feature. @xref{Integer Conversions}, for
  1566. details.
  1567. @item @samp{%o}
  1568. Print an integer as an unsigned octal number. @xref{Integer
  1569. Conversions}, for details.
  1570. @item @samp{%u}
  1571. Print an integer as an unsigned decimal number. @xref{Integer
  1572. Conversions}, for details.
  1573. @item @samp{%x}, @samp{%X}
  1574. Print an integer as an unsigned hexadecimal number. @samp{%x} uses
  1575. lower-case letters and @samp{%X} uses upper-case. @xref{Integer
  1576. Conversions}, for details.
  1577. @item @samp{%f}, @samp{%F}
  1578. Print a floating-point number in normal (fixed-point) notation.
  1579. @samp{%f} uses lower-case letters and @samp{%F} uses upper-case.
  1580. @xref{Floating-Point Conversions}, for details.
  1581. @item @samp{%e}, @samp{%E}
  1582. Print a floating-point number in exponential notation. @samp{%e} uses
  1583. lower-case letters and @samp{%E} uses upper-case. @xref{Floating-Point
  1584. Conversions}, for details.
  1585. @item @samp{%g}, @samp{%G}
  1586. Print a floating-point number in either normal or exponential notation,
  1587. whichever is more appropriate for its magnitude. @samp{%g} uses
  1588. lower-case letters and @samp{%G} uses upper-case. @xref{Floating-Point
  1589. Conversions}, for details.
  1590. @item @samp{%a}, @samp{%A}
  1591. Print a floating-point number in a hexadecimal fractional notation with
  1592. the exponent to base 2 represented in decimal digits. @samp{%a} uses
  1593. lower-case letters and @samp{%A} uses upper-case. @xref{Floating-Point
  1594. Conversions}, for details.
  1595. @item @samp{%c}
  1596. Print a single character. @xref{Other Output Conversions}.
  1597. @item @samp{%C}
  1598. This is an alias for @samp{%lc} which is supported for compatibility
  1599. with the Unix standard.
  1600. @item @samp{%s}
  1601. Print a string. @xref{Other Output Conversions}.
  1602. @item @samp{%S}
  1603. This is an alias for @samp{%ls} which is supported for compatibility
  1604. with the Unix standard.
  1605. @item @samp{%p}
  1606. Print the value of a pointer. @xref{Other Output Conversions}.
  1607. @item @samp{%n}
  1608. Get the number of characters printed so far. @xref{Other Output Conversions}.
  1609. Note that this conversion specification never produces any output.
  1610. @item @samp{%m}
  1611. Print the string corresponding to the value of @code{errno}.
  1612. (This is a GNU extension.)
  1613. @xref{Other Output Conversions}.
  1614. @item @samp{%%}
  1615. Print a literal @samp{%} character. @xref{Other Output Conversions}.
  1616. @end table
  1617. If the syntax of a conversion specification is invalid, unpredictable
  1618. things will happen, so don't do this. If there aren't enough function
  1619. arguments provided to supply values for all the conversion
  1620. specifications in the template string, or if the arguments are not of
  1621. the correct types, the results are unpredictable. If you supply more
  1622. arguments than conversion specifications, the extra argument values are
  1623. simply ignored; this is sometimes useful.
  1624. @node Integer Conversions
  1625. @subsection Integer Conversions
  1626. This section describes the options for the @samp{%d}, @samp{%i},
  1627. @samp{%b}, @samp{%B}, @samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X} conversion
  1628. specifications. These conversions print integers in various formats.
  1629. The @samp{%d} and @samp{%i} conversion specifications both print an
  1630. @code{int} argument as a signed decimal number; while @samp{%b}, @samp{%o},
  1631. @samp{%u}, and @samp{%x} print the argument as an unsigned binary, octal,
  1632. decimal, or hexadecimal number (respectively). The @samp{%X} conversion
  1633. specification is just like @samp{%x} except that it uses the characters
  1634. @samp{ABCDEF} as digits instead of @samp{abcdef}. The @samp{%B}
  1635. conversion specification is just like @samp{%b} except that, with the
  1636. @samp{#} flag, the output starts with @samp{0B} instead of @samp{0b}.
  1637. The following flags are meaningful:
  1638. @table @asis
  1639. @item @samp{-}
  1640. Left-justify the result in the field (instead of the normal
  1641. right-justification).
  1642. @item @samp{+}
  1643. For the signed @samp{%d} and @samp{%i} conversions, print a
  1644. plus sign if the value is positive.
  1645. @item @samp{ }
  1646. For the signed @samp{%d} and @samp{%i} conversions, if the result
  1647. doesn't start with a plus or minus sign, prefix it with a space
  1648. character instead. Since the @samp{+} flag ensures that the result
  1649. includes a sign, this flag is ignored if you supply both of them.
  1650. @item @samp{#}
  1651. For the @samp{%o} conversion, this forces the leading digit to be
  1652. @samp{0}, as if by increasing the precision. For @samp{%x} or
  1653. @samp{%X}, this prefixes a leading @samp{0x} or @samp{0X}
  1654. (respectively) to the result. For @samp{%b} or @samp{%B}, this
  1655. prefixes a leading @samp{0b} or @samp{0B} (respectively)
  1656. to the result. This doesn't do anything useful for the @samp{%d},
  1657. @samp{%i}, or @samp{%u} conversions. Using this flag produces output
  1658. which can be parsed by the @code{strtoul} function (@pxref{Parsing of
  1659. Integers}) and @code{scanf} with the @samp{%i} conversion
  1660. (@pxref{Numeric Input Conversions}).
  1661. For the @samp{%m} conversion, print an error constant or decimal error
  1662. number, instead of a (possibly translated) error message.
  1663. @item @samp{'}
  1664. Separate the digits into groups as specified by the locale specified for
  1665. the @code{LC_NUMERIC} category; @pxref{General Numeric}. This flag is a
  1666. GNU extension.
  1667. @item @samp{0}
  1668. Pad the field with zeros instead of spaces. The zeros are placed after
  1669. any indication of sign or base. This flag is ignored if the @samp{-}
  1670. flag is also specified, or if a precision is specified.
  1671. @end table
  1672. If a precision is supplied, it specifies the minimum number of digits to
  1673. appear; leading zeros are produced if necessary. If you don't specify a
  1674. precision, the number is printed with as many digits as it needs. If
  1675. you convert a value of zero with an explicit precision of zero, then no
  1676. characters at all are produced.
  1677. Without a type modifier, the corresponding argument is treated as an
  1678. @code{int} (for the signed conversions @samp{%i} and @samp{%d}) or
  1679. @code{unsigned int} (for the unsigned conversions @samp{%b},
  1680. @samp{%B}, @samp{%o}, @samp{%u},
  1681. @samp{%x}, and @samp{%X}). Recall that since @code{printf} and friends
  1682. are variadic, any @code{char} and @code{short} arguments are
  1683. automatically converted to @code{int} by the default argument
  1684. promotions. For arguments of other integer types, you can use these
  1685. modifiers:
  1686. @table @samp
  1687. @item hh
  1688. Specifies that the argument is a @code{signed char} or @code{unsigned
  1689. char}, as appropriate. A @code{char} argument is converted to an
  1690. @code{int} or @code{unsigned int} by the default argument promotions
  1691. anyway, but the @samp{hh} modifier says to convert it back to a
  1692. @code{char} again.
  1693. This modifier was introduced in @w{ISO C99}.
  1694. @item h
  1695. Specifies that the argument is a @code{short int} or @code{unsigned
  1696. short int}, as appropriate. A @code{short} argument is converted to an
  1697. @code{int} or @code{unsigned int} by the default argument promotions
  1698. anyway, but the @samp{h} modifier says to convert it back to a
  1699. @code{short} again.
  1700. @item j
  1701. Specifies that the argument is a @code{intmax_t} or @code{uintmax_t}, as
  1702. appropriate.
  1703. This modifier was introduced in @w{ISO C99}.
  1704. @item l
  1705. Specifies that the argument is a @code{long int} or @code{unsigned long
  1706. int}, as appropriate. Two @samp{l} characters are like the @samp{L}
  1707. modifier, below.
  1708. If used with @samp{%c} or @samp{%s} the corresponding parameter is
  1709. considered as a wide character or wide character string respectively.
  1710. This use of @samp{l} was introduced in @w{Amendment 1} to @w{ISO C90}.
  1711. @item L
  1712. @itemx ll
  1713. @itemx q
  1714. Specifies that the argument is a @code{long long int}. (This type is
  1715. an extension supported by the GNU C compiler. On systems that don't
  1716. support extra-long integers, this is the same as @code{long int}.)
  1717. The @samp{q} modifier is another name for the same thing, which comes
  1718. from 4.4 BSD; a @w{@code{long long int}} is sometimes called a ``quad''
  1719. @code{int}.
  1720. @item t
  1721. Specifies that the argument is a @code{ptrdiff_t}.
  1722. This modifier was introduced in @w{ISO C99}.
  1723. @item w@var{n}
  1724. Specifies that the argument is a @code{int@var{n}_t} or
  1725. @code{int_least@var{n}_t} (which are the same type), for conversions
  1726. taking signed integers, or @code{uint@var{n}_t} or
  1727. @code{uint_least@var{n}_t} (which are the same type), for conversions
  1728. taking unsigned integers. If the type is narrower than @code{int},
  1729. the promoted argument is converted back to the specified type.
  1730. This modifier was introduced in @w{ISO C23}.
  1731. @item wf@var{n}
  1732. Specifies that the argument is a @code{int_fast@var{n}_t} or
  1733. @code{uint_fast@var{n}_t}, as appropriate. If the type is narrower
  1734. than @code{int}, the promoted argument is converted back to the
  1735. specified type.
  1736. This modifier was introduced in @w{ISO C23}.
  1737. @item z
  1738. @itemx Z
  1739. Specifies that the argument is a @code{size_t}.
  1740. @samp{z} was introduced in @w{ISO C99}. @samp{Z} is a GNU extension
  1741. predating this addition and should not be used in new code.
  1742. @end table
  1743. Here is an example. Using the template string:
  1744. @smallexample
  1745. "|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"
  1746. @end smallexample
  1747. @noindent
  1748. to print numbers using the different options for the @samp{%d}
  1749. conversion gives results like:
  1750. @smallexample
  1751. | 0|0 | +0|+0 | 0|00000| | 00|0|
  1752. | 1|1 | +1|+1 | 1|00001| 1| 01|1|
  1753. | -1|-1 | -1|-1 | -1|-0001| -1| -01|-1|
  1754. |100000|100000|+100000|+100000| 100000|100000|100000|100000|100000|
  1755. @end smallexample
  1756. In particular, notice what happens in the last case where the number
  1757. is too large to fit in the minimum field width specified.
  1758. Here are some more examples showing how unsigned integers print under
  1759. various format options, using the template string:
  1760. @smallexample
  1761. "|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n"
  1762. @end smallexample
  1763. @smallexample
  1764. | 0| 0| 0| 0| 0| 0| 0| 00000000|
  1765. | 1| 1| 1| 1| 01| 0x1| 0X1|0x00000001|
  1766. |100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0|
  1767. @end smallexample
  1768. @node Floating-Point Conversions
  1769. @subsection Floating-Point Conversions
  1770. This section discusses the conversion specifications for floating-point
  1771. numbers: the @samp{%f}, @samp{%F}, @samp{%e}, @samp{%E}, @samp{%g}, and
  1772. @samp{%G} conversions.
  1773. The @samp{%f} and @samp{%F} conversions print their argument in fixed-point
  1774. notation, producing output of the form
  1775. @w{[@code{-}]@var{ddd}@code{.}@var{ddd}},
  1776. where the number of digits following the decimal point is controlled
  1777. by the precision you specify.
  1778. The @samp{%e} conversion prints its argument in exponential notation,
  1779. producing output of the form
  1780. @w{[@code{-}]@var{d}@code{.}@var{ddd}@code{e}[@code{+}|@code{-}]@var{dd}}.
  1781. Again, the number of digits following the decimal point is controlled by
  1782. the precision. The exponent always contains at least two digits. The
  1783. @samp{%E} conversion is similar but the exponent is marked with the letter
  1784. @samp{E} instead of @samp{e}.
  1785. The @samp{%g} and @samp{%G} conversions print the argument in the style
  1786. of @samp{%e} or @samp{%E} (respectively) if the exponent would be less
  1787. than -4 or greater than or equal to the precision; otherwise they use
  1788. the @samp{%f} or @samp{%F} style. A precision of @code{0}, is taken as 1.
  1789. Trailing zeros are removed from the fractional portion of the result and
  1790. a decimal-point character appears only if it is followed by a digit.
  1791. The @samp{%a} and @samp{%A} conversions are meant for representing
  1792. floating-point numbers exactly in textual form so that they can be
  1793. exchanged as texts between different programs and/or machines. The
  1794. numbers are represented in the form
  1795. @w{[@code{-}]@code{0x}@var{h}@code{.}@var{hhh}@code{p}[@code{+}|@code{-}]@var{dd}}.
  1796. At the left of the decimal-point character exactly one digit is print.
  1797. This character is only @code{0} if the number is denormalized.
  1798. Otherwise the value is unspecified; it is implementation dependent how many
  1799. bits are used. The number of hexadecimal digits on the right side of
  1800. the decimal-point character is equal to the precision. If the precision
  1801. is zero it is determined to be large enough to provide an exact
  1802. representation of the number (or it is large enough to distinguish two
  1803. adjacent values if the @code{FLT_RADIX} is not a power of 2,
  1804. @pxref{Floating Point Parameters}). For the @samp{%a} conversion
  1805. lower-case characters are used to represent the hexadecimal number and
  1806. the prefix and exponent sign are printed as @code{0x} and @code{p}
  1807. respectively. Otherwise upper-case characters are used and @code{0X}
  1808. and @code{P} are used for the representation of prefix and exponent
  1809. string. The exponent to the base of two is printed as a decimal number
  1810. using at least one digit but at most as many digits as necessary to
  1811. represent the value exactly.
  1812. If the value to be printed represents infinity or a NaN, the output is
  1813. @w{[@code{-}]@code{inf}} or @code{nan} respectively if the conversion
  1814. specifier is @samp{%a}, @samp{%e}, @samp{%f}, or @samp{%g} and it is
  1815. @w{[@code{-}]@code{INF}} or @code{NAN} respectively if the conversion is
  1816. @samp{%A}, @samp{%E}, @samp{%F} or @samp{%G}. On some implementations, a NaN
  1817. may result in longer output with information about the payload of the
  1818. NaN; ISO C23 defines a macro @code{_PRINTF_NAN_LEN_MAX} giving the
  1819. maximum length of such output.
  1820. The following flags can be used to modify the behavior:
  1821. @comment We use @asis instead of @samp so we can have ` ' as an item.
  1822. @table @asis
  1823. @item @samp{-}
  1824. Left-justify the result in the field. Normally the result is
  1825. right-justified.
  1826. @item @samp{+}
  1827. Always include a plus or minus sign in the result.
  1828. @item @samp{ }
  1829. If the result doesn't start with a plus or minus sign, prefix it with a
  1830. space instead. Since the @samp{+} flag ensures that the result includes
  1831. a sign, this flag is ignored if you supply both of them.
  1832. @item @samp{#}
  1833. Specifies that the result should always include a decimal point, even
  1834. if no digits follow it. For the @samp{%g} and @samp{%G} conversions,
  1835. this also forces trailing zeros after the decimal point to be left
  1836. in place where they would otherwise be removed.
  1837. @item @samp{'}
  1838. Separate the digits of the integer part of the result into groups as
  1839. specified by the locale specified for the @code{LC_NUMERIC} category;
  1840. @pxref{General Numeric}. This flag is a GNU extension.
  1841. @item @samp{0}
  1842. Pad the field with zeros instead of spaces; the zeros are placed
  1843. after any sign. This flag is ignored if the @samp{-} flag is also
  1844. specified.
  1845. @end table
  1846. The precision specifies how many digits follow the decimal-point
  1847. character for the @samp{%f}, @samp{%F}, @samp{%e}, and @samp{%E} conversions.
  1848. For these conversions, the default precision is @code{6}. If the precision
  1849. is explicitly @code{0}, this suppresses the decimal point character
  1850. entirely. For the @samp{%g} and @samp{%G} conversions, the precision
  1851. specifies how many significant digits to print. Significant digits are
  1852. the first digit before the decimal point, and all the digits after it.
  1853. If the precision is @code{0} or not specified for @samp{%g} or @samp{%G},
  1854. it is treated like a value of @code{1}. If the value being printed
  1855. cannot be expressed accurately in the specified number of digits, the
  1856. value is rounded to the nearest number that fits.
  1857. Without a type modifier, the floating-point conversions use an argument
  1858. of type @code{double}. (By the default argument promotions, any
  1859. @code{float} arguments are automatically converted to @code{double}.)
  1860. The following type modifier is supported:
  1861. @table @samp
  1862. @item L
  1863. An uppercase @samp{L} specifies that the argument is a @code{long
  1864. double}.
  1865. @end table
  1866. Here are some examples showing how numbers print using the various
  1867. floating-point conversions. All of the numbers were printed using
  1868. this template string:
  1869. @smallexample
  1870. "|%13.4a|%13.4f|%13.4e|%13.4g|\n"
  1871. @end smallexample
  1872. Here is the output:
  1873. @smallexample
  1874. | 0x0.0000p+0| 0.0000| 0.0000e+00| 0|
  1875. | 0x1.0000p-1| 0.5000| 5.0000e-01| 0.5|
  1876. | 0x1.0000p+0| 1.0000| 1.0000e+00| 1|
  1877. | -0x1.0000p+0| -1.0000| -1.0000e+00| -1|
  1878. | 0x1.9000p+6| 100.0000| 1.0000e+02| 100|
  1879. | 0x1.f400p+9| 1000.0000| 1.0000e+03| 1000|
  1880. | 0x1.3880p+13| 10000.0000| 1.0000e+04| 1e+04|
  1881. | 0x1.81c8p+13| 12345.0000| 1.2345e+04| 1.234e+04|
  1882. | 0x1.86a0p+16| 100000.0000| 1.0000e+05| 1e+05|
  1883. | 0x1.e240p+16| 123456.0000| 1.2346e+05| 1.235e+05|
  1884. @end smallexample
  1885. Notice how the @samp{%g} conversion drops trailing zeros.
  1886. @node Other Output Conversions
  1887. @subsection Other Output Conversions
  1888. This section describes miscellaneous conversions for @code{printf}.
  1889. The @samp{%c} conversion prints a single character. In case there is no
  1890. @samp{l} modifier the @code{int} argument is first converted to an
  1891. @code{unsigned char}. Then, if used in a wide stream function, the
  1892. character is converted into the corresponding wide character. The
  1893. @samp{-} flag can be used to specify left-justification in the field,
  1894. but no other flags are defined, and no precision or type modifier can be
  1895. given. For example:
  1896. @smallexample
  1897. printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');
  1898. @end smallexample
  1899. @noindent
  1900. prints @samp{hello}.
  1901. If there is an @samp{l} modifier present the argument is expected to be
  1902. of type @code{wint_t}. If used in a multibyte function the wide
  1903. character is converted into a multibyte character before being added to
  1904. the output. In this case more than one output byte can be produced.
  1905. The @samp{%s} conversion prints a string. If no @samp{l} modifier is
  1906. present the corresponding argument must be of type @code{char *} (or
  1907. @code{const char *}). If used in a wide stream function the string is
  1908. first converted to a wide character string. A precision can be
  1909. specified to indicate the maximum number of characters to write;
  1910. otherwise characters in the string up to but not including the
  1911. terminating null character are written to the output stream. The
  1912. @samp{-} flag can be used to specify left-justification in the field,
  1913. but no other flags or type modifiers are defined for this conversion.
  1914. For example:
  1915. @smallexample
  1916. printf ("%3s%-6s", "no", "where");
  1917. @end smallexample
  1918. @noindent
  1919. prints @samp{ nowhere }.
  1920. If there is an @samp{l} modifier present, the argument is expected to
  1921. be of type @code{wchar_t} (or @code{const wchar_t *}).
  1922. If you accidentally pass a null pointer as the argument for a @samp{%s}
  1923. conversion, @theglibc{} prints it as @samp{(null)}. We think this
  1924. is more useful than crashing. But it's not good practice to pass a null
  1925. argument intentionally.
  1926. The @samp{%m} conversion prints the string corresponding to the error
  1927. code in @code{errno}. @xref{Error Messages}. Thus:
  1928. @smallexample
  1929. fprintf (stderr, "can't open `%s': %m\n", filename);
  1930. @end smallexample
  1931. @noindent
  1932. is equivalent to:
  1933. @smallexample
  1934. fprintf (stderr, "can't open `%s': %s\n", filename, strerror (errno));
  1935. @end smallexample
  1936. The @samp{%m} conversion can be used with the @samp{#} flag to print an
  1937. error constant, as provided by @code{strerrorname_np}. Both @samp{%m}
  1938. and @samp{%#m} are @glibcadj{} extensions.
  1939. The @samp{%p} conversion prints a pointer value. The corresponding
  1940. argument must be of type @code{void *}. In practice, you can use any
  1941. type of pointer.
  1942. In @theglibc{}, non-null pointers are printed as unsigned integers,
  1943. as if a @samp{%#x} conversion were used. Null pointers print as
  1944. @samp{(nil)}. (Pointers might print differently in other systems.)
  1945. For example:
  1946. @smallexample
  1947. printf ("%p", "testing");
  1948. @end smallexample
  1949. @noindent
  1950. prints @samp{0x} followed by a hexadecimal number---the address of the
  1951. string constant @code{"testing"}. It does not print the word
  1952. @samp{testing}.
  1953. You can supply the @samp{-} flag with the @samp{%p} conversion to
  1954. specify left-justification, but no other flags, precision, or type
  1955. modifiers are defined.
  1956. The @samp{%n} conversion is unlike any of the other output conversions.
  1957. It uses an argument which must be a pointer to an @code{int}, but
  1958. instead of printing anything it stores the number of characters printed
  1959. so far by this call at that location. The @samp{h} and @samp{l} type
  1960. modifiers are permitted to specify that the argument is of type
  1961. @code{short int *} or @code{long int *} instead of @code{int *}, but no
  1962. flags, field width, or precision are permitted.
  1963. For example,
  1964. @smallexample
  1965. int nchar;
  1966. printf ("%d %s%n\n", 3, "bears", &nchar);
  1967. @end smallexample
  1968. @noindent
  1969. prints:
  1970. @smallexample
  1971. 3 bears
  1972. @end smallexample
  1973. @noindent
  1974. and sets @code{nchar} to @code{7}, because @samp{3 bears} is seven
  1975. characters.
  1976. The @samp{%%} conversion prints a literal @samp{%} character. This
  1977. conversion doesn't use an argument, and no flags, field width,
  1978. precision, or type modifiers are permitted.
  1979. @node Formatted Output Functions
  1980. @subsection Formatted Output Functions
  1981. This section describes how to call @code{printf} and related functions.
  1982. Prototypes for these functions are in the header file @file{stdio.h}.
  1983. Because these functions take a variable number of arguments, you
  1984. @emph{must} declare prototypes for them before using them. Of course,
  1985. the easiest way to make sure you have all the right prototypes is to
  1986. just include @file{stdio.h}.
  1987. @pindex stdio.h
  1988. The @code{printf} family shares the error codes listed below.
  1989. Individual functions may report additional @code{errno} values if they
  1990. fail.
  1991. @table @code
  1992. @item EOVERFLOW
  1993. The number of written bytes would have exceeded @code{INT_MAX}, and thus
  1994. could not be represented in the return type @code{int}.
  1995. @item ENOMEM
  1996. The function could not allocate memory during processing. Long argument
  1997. lists and certain floating point conversions may require memory
  1998. allocation, as does initialization of an output stream upon first use.
  1999. @item EILSEQ
  2000. POSIX specifies this error code should be used if a wide character is
  2001. encountered that does not have a matching valid character. @Theglibc{}
  2002. always performs transliteration, using a replacement character if
  2003. necessary, so this error condition cannot occur on output. However,
  2004. @theglibc{} uses @code{EILSEQ} to indicate that an input character
  2005. sequence (wide or multi-byte) could not be converted successfully.
  2006. @end table
  2007. @deftypefun int printf (const char *@var{template}, @dots{})
  2008. @standards{ISO, stdio.h}
  2009. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2010. The @code{printf} function prints the optional arguments under the
  2011. control of the template string @var{template} to the stream
  2012. @code{stdout}. It returns the number of characters printed, or a
  2013. negative value if there was an output error.
  2014. @end deftypefun
  2015. @deftypefun int wprintf (const wchar_t *@var{template}, @dots{})
  2016. @standards{ISO, wchar.h}
  2017. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2018. The @code{wprintf} function prints the optional arguments under the
  2019. control of the wide template string @var{template} to the stream
  2020. @code{stdout}. It returns the number of wide characters printed, or a
  2021. negative value if there was an output error.
  2022. @end deftypefun
  2023. @deftypefun int fprintf (FILE *@var{stream}, const char *@var{template}, @dots{})
  2024. @standards{ISO, stdio.h}
  2025. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2026. This function is just like @code{printf}, except that the output is
  2027. written to the stream @var{stream} instead of @code{stdout}.
  2028. @end deftypefun
  2029. @deftypefun int fwprintf (FILE *@var{stream}, const wchar_t *@var{template}, @dots{})
  2030. @standards{ISO, wchar.h}
  2031. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2032. This function is just like @code{wprintf}, except that the output is
  2033. written to the stream @var{stream} instead of @code{stdout}.
  2034. @end deftypefun
  2035. @deftypefun int sprintf (char *@var{s}, const char *@var{template}, @dots{})
  2036. @standards{ISO, stdio.h}
  2037. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2038. This is like @code{printf}, except that the output is stored in the character
  2039. array @var{s} instead of written to a stream. A null character is written
  2040. to mark the end of the string.
  2041. The @code{sprintf} function returns the number of characters stored in
  2042. the array @var{s}, not including the terminating null character.
  2043. The behavior of this function is undefined if copying takes place
  2044. between objects that overlap---for example, if @var{s} is also given
  2045. as an argument to be printed under control of the @samp{%s} conversion.
  2046. @xref{Copying Strings and Arrays}.
  2047. @strong{Warning:} The @code{sprintf} function can be @strong{dangerous}
  2048. because it can potentially output more characters than can fit in the
  2049. allocation size of the string @var{s}. Remember that the field width
  2050. given in a conversion specification is only a @emph{minimum} value.
  2051. To avoid this problem, you can use @code{snprintf} or @code{asprintf},
  2052. described below.
  2053. @end deftypefun
  2054. @deftypefun int swprintf (wchar_t *@var{ws}, size_t @var{size}, const wchar_t *@var{template}, @dots{})
  2055. @standards{GNU, wchar.h}
  2056. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2057. This is like @code{wprintf}, except that the output is stored in the
  2058. wide character array @var{ws} instead of written to a stream. A null
  2059. wide character is written to mark the end of the string. The @var{size}
  2060. argument specifies the maximum number of characters to produce. The
  2061. trailing null character is counted towards this limit, so you should
  2062. allocate at least @var{size} wide characters for the string @var{ws}.
  2063. The return value is the number of characters generated for the given
  2064. input, excluding the trailing null. If not all output fits into the
  2065. provided buffer a negative value is returned, and @code{errno} is set to
  2066. @code{E2BIG}. (The setting of @code{errno} is a GNU extension.) You
  2067. should try again with a bigger output string. @emph{Note:} this is
  2068. different from how @code{snprintf} handles this situation.
  2069. Note that the corresponding narrow stream function takes fewer
  2070. parameters. @code{swprintf} in fact corresponds to the @code{snprintf}
  2071. function. Since the @code{sprintf} function can be dangerous and should
  2072. be avoided the @w{ISO C} committee refused to make the same mistake
  2073. again and decided to not define a function exactly corresponding to
  2074. @code{sprintf}.
  2075. @end deftypefun
  2076. @deftypefun int snprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, @dots{})
  2077. @standards{GNU, stdio.h}
  2078. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2079. The @code{snprintf} function is similar to @code{sprintf}, except that
  2080. the @var{size} argument specifies the maximum number of characters to
  2081. produce. The trailing null character is counted towards this limit, so
  2082. you should allocate at least @var{size} characters for the string @var{s}.
  2083. If @var{size} is zero, nothing, not even the null byte, shall be written and
  2084. @var{s} may be a null pointer.
  2085. The return value is the number of characters which would be generated
  2086. for the given input, excluding the trailing null. If this value is
  2087. greater than or equal to @var{size}, not all characters from the result have
  2088. been stored in @var{s}. If this happens, you should be wary of using
  2089. the truncated result as that could lead to security, encoding, or
  2090. other bugs in your program (@pxref{Truncating Strings}).
  2091. Instead, you should try again with a bigger output
  2092. string. Here is an example of doing this:
  2093. @smallexample
  2094. @group
  2095. /* @r{Construct a message describing the value of a variable}
  2096. @r{whose name is @var{name} and whose value is @var{value}.} */
  2097. char *
  2098. make_message (char *name, char *value)
  2099. @{
  2100. /* @r{Guess we need no more than 100 bytes of space.} */
  2101. size_t size = 100;
  2102. char *buffer = xmalloc (size);
  2103. @end group
  2104. @group
  2105. /* @r{Try to print in the allocated space.} */
  2106. int buflen = snprintf (buffer, size, "value of %s is %s",
  2107. name, value);
  2108. if (! (0 <= buflen && buflen < SIZE_MAX))
  2109. fatal ("integer overflow");
  2110. @end group
  2111. @group
  2112. if (buflen >= size)
  2113. @{
  2114. /* @r{Reallocate buffer now that we know
  2115. how much space is needed.} */
  2116. size = buflen;
  2117. size++;
  2118. buffer = xrealloc (buffer, size);
  2119. /* @r{Try again.} */
  2120. snprintf (buffer, size, "value of %s is %s",
  2121. name, value);
  2122. @}
  2123. /* @r{The last call worked, return the string.} */
  2124. return buffer;
  2125. @}
  2126. @end group
  2127. @end smallexample
  2128. In practice, it is often easier just to use @code{asprintf}, below.
  2129. @strong{Attention:} In versions of @theglibc{} prior to 2.1 the
  2130. return value is the number of characters stored, not including the
  2131. terminating null; unless there was not enough space in @var{s} to
  2132. store the result in which case @code{-1} is returned. This was
  2133. changed in order to comply with the @w{ISO C99} standard.
  2134. @end deftypefun
  2135. @deftypefun int dprintf (int @var{fd}, @var{template}, ...)
  2136. @standards{POSIX, stdio.h}
  2137. @safety{@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2138. This function formats its arguments according to @var{template} and
  2139. writes the result to the file descriptor @var{fd}, using the
  2140. @code{write} function. It returns the number of bytes written, or a
  2141. negative value if there was an error. In the error case, @code{errno}
  2142. is set appropriately. The possible @code{errno} values depend on the
  2143. type of the file descriptor @var{fd}, in addition to the general
  2144. @code{printf} error codes.
  2145. The number of calls to @code{write} is unspecified, and some @code{write}
  2146. calls may have happened even if @code{dprintf} returns with an error.
  2147. @strong{Portability Note:} POSIX does not require that this function is
  2148. async-signal-safe, and @theglibc{} implementation is not. However, some
  2149. other systems offer this function as an async-signal-safe alternative to
  2150. @code{fprintf}. @xref{POSIX Safety Concepts}.
  2151. @end deftypefun
  2152. @node Dynamic Output
  2153. @subsection Dynamically Allocating Formatted Output
  2154. The functions in this section do formatted output and place the results
  2155. in dynamically allocated memory.
  2156. @deftypefun int asprintf (char **@var{ptr}, const char *@var{template}, @dots{})
  2157. @standards{GNU, stdio.h}
  2158. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2159. This function is similar to @code{sprintf}, except that it dynamically
  2160. allocates a string (as with @code{malloc}; @pxref{Unconstrained
  2161. Allocation}) to hold the output, instead of putting the output in a
  2162. buffer you allocate in advance. The @var{ptr} argument should be the
  2163. address of a @code{char *} object, and a successful call to
  2164. @code{asprintf} stores a pointer to the newly allocated string at that
  2165. location. Current and future versions of @theglibc{} write a null
  2166. pointer to @samp{*@var{ptr}} upon failure. To achieve similar
  2167. behavior with previous versions, initialize @samp{*@var{ptr}} to a
  2168. null pointer before calling @code{asprintf}. (Specifications for
  2169. @code{asprintf} only require a valid pointer value in
  2170. @samp{*@var{ptr}} if @code{asprintf} succeeds, but no implementations
  2171. are known which overwrite a null pointer with a pointer that cannot be
  2172. freed on failure.)
  2173. The return value is the number of characters allocated for the buffer, or
  2174. less than zero if an error occurred. Usually this means that the buffer
  2175. could not be allocated.
  2176. Here is how to use @code{asprintf} to get the same result as the
  2177. @code{snprintf} example, but more easily:
  2178. @smallexample
  2179. /* @r{Construct a message describing the value of a variable}
  2180. @r{whose name is @var{name} and whose value is @var{value}.} */
  2181. char *
  2182. make_message (char *name, char *value)
  2183. @{
  2184. char *result;
  2185. if (asprintf (&result, "value of %s is %s", name, value) < 0)
  2186. return NULL;
  2187. return result;
  2188. @}
  2189. @end smallexample
  2190. @end deftypefun
  2191. @deftypefun int obstack_printf (struct obstack *@var{obstack}, const char *@var{template}, @dots{})
  2192. @standards{GNU, stdio.h}
  2193. @safety{@prelim{}@mtsafe{@mtsrace{:obstack} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  2194. This function is similar to @code{asprintf}, except that it uses the
  2195. obstack @var{obstack} to allocate the space. @xref{Obstacks}.
  2196. The characters are written onto the end of the current object.
  2197. To get at them, you must finish the object with @code{obstack_finish}
  2198. (@pxref{Growing Objects}).
  2199. @end deftypefun
  2200. @node Variable Arguments Output
  2201. @subsection Variable Arguments Output Functions
  2202. The functions @code{vprintf} and friends are provided so that you can
  2203. define your own variadic @code{printf}-like functions that make use of
  2204. the same internals as the built-in formatted output functions.
  2205. The most natural way to define such functions would be to use a language
  2206. construct to say, ``Call @code{printf} and pass this template plus all
  2207. of my arguments after the first five.'' But there is no way to do this
  2208. in C, and it would be hard to provide a way, since at the C language
  2209. level there is no way to tell how many arguments your function received.
  2210. Since that method is impossible, we provide alternative functions, the
  2211. @code{vprintf} series, which lets you pass a @code{va_list} to describe
  2212. ``all of my arguments after the first five.''
  2213. When it is sufficient to define a macro rather than a real function,
  2214. the GNU C compiler provides a way to do this much more easily with macros.
  2215. For example:
  2216. @smallexample
  2217. #define myprintf(a, b, c, d, e, rest...) \
  2218. printf (mytemplate , ## rest)
  2219. @end smallexample
  2220. @noindent
  2221. @xref{Variadic Macros,,, cpp, The C preprocessor}, for details.
  2222. But this is limited to macros, and does not apply to real functions at all.
  2223. Before calling @code{vprintf} or the other functions listed in this
  2224. section, you @emph{must} call @code{va_start} (@pxref{Variadic
  2225. Functions}) to initialize a pointer to the variable arguments. Then you
  2226. can call @code{va_arg} to fetch the arguments that you want to handle
  2227. yourself. This advances the pointer past those arguments.
  2228. Once your @code{va_list} pointer is pointing at the argument of your
  2229. choice, you are ready to call @code{vprintf}. That argument and all
  2230. subsequent arguments that were passed to your function are used by
  2231. @code{vprintf} along with the template that you specified separately.
  2232. @strong{Portability Note:} The value of the @code{va_list} pointer is
  2233. undetermined after the call to @code{vprintf}, so you must not use
  2234. @code{va_arg} after you call @code{vprintf}. Instead, you should call
  2235. @code{va_end} to retire the pointer from service. You can call
  2236. @code{va_start} again and begin fetching the arguments from the start of
  2237. the variable argument list. (Alternatively, you can use @code{va_copy}
  2238. to make a copy of the @code{va_list} pointer before calling
  2239. @code{vfprintf}.) Calling @code{vprintf} does not destroy the argument
  2240. list of your function, merely the particular pointer that you passed to
  2241. it.
  2242. Prototypes for these functions are declared in @file{stdio.h}.
  2243. @pindex stdio.h
  2244. @deftypefun int vprintf (const char *@var{template}, va_list @var{ap})
  2245. @standards{ISO, stdio.h}
  2246. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2247. This function is similar to @code{printf} except that, instead of taking
  2248. a variable number of arguments directly, it takes an argument list
  2249. pointer @var{ap}.
  2250. @end deftypefun
  2251. @deftypefun int vwprintf (const wchar_t *@var{template}, va_list @var{ap})
  2252. @standards{ISO, wchar.h}
  2253. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2254. This function is similar to @code{wprintf} except that, instead of taking
  2255. a variable number of arguments directly, it takes an argument list
  2256. pointer @var{ap}.
  2257. @end deftypefun
  2258. @deftypefun int vfprintf (FILE *@var{stream}, const char *@var{template}, va_list @var{ap})
  2259. @standards{ISO, stdio.h}
  2260. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2261. @c Although vfprintf sets up a cleanup region to release the lock on the
  2262. @c output stream, it doesn't use it to release args_value or string in
  2263. @c case of cancellation. This doesn't make it unsafe, but cancelling it
  2264. @c may leak memory. The unguarded use of __printf_function_table is
  2265. @c also of concern for all callers.
  2266. @c _itoa ok
  2267. @c _udiv_qrnnd_preinv ok
  2268. @c group_number ok
  2269. @c _i18n_number_rewrite
  2270. @c __wctrans ok
  2271. @c __towctrans @mtslocale
  2272. @c __wcrtomb ok? dup below
  2273. @c outdigit_value ok
  2274. @c outdigitwc_value ok
  2275. @c outchar ok
  2276. @c outstring ok
  2277. @c PAD ok
  2278. @c __printf_fp @mtslocale @ascuheap @acsmem
  2279. @c __printf_fphex @mtslocale
  2280. @c __readonly_area
  2281. @c [GNU/Linux] fopen, strtoul, free
  2282. @c __strerror_r ok if no translation, check otherwise
  2283. @c __btowc ? gconv-modules
  2284. @c __wcrtomb ok (not using internal state) gconv-modules
  2285. @c ARGCHECK
  2286. @c UNBUFFERED_P (tested before taking the stream lock)
  2287. @c buffered_vfprintf ok
  2288. @c __find_spec(wc|mb)
  2289. @c read_int
  2290. @c __libc_use_alloca
  2291. @c process_arg
  2292. @c process_string_arg
  2293. @c __parse_one_spec(wc|mb)
  2294. @c *__printf_arginfo_table unguarded
  2295. @c __printf_va_arg_table-> unguarded
  2296. @c *__printf_function_table unguarded
  2297. @c done_add
  2298. @c printf_unknown
  2299. @c outchar
  2300. @c _itoa_word
  2301. This is the equivalent of @code{fprintf} with the variable argument list
  2302. specified directly as for @code{vprintf}.
  2303. @end deftypefun
  2304. @deftypefun int vfwprintf (FILE *@var{stream}, const wchar_t *@var{template}, va_list @var{ap})
  2305. @standards{ISO, wchar.h}
  2306. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  2307. This is the equivalent of @code{fwprintf} with the variable argument list
  2308. specified directly as for @code{vwprintf}.
  2309. @end deftypefun
  2310. @deftypefun int vsprintf (char *@var{s}, const char *@var{template}, va_list @var{ap})
  2311. @standards{ISO, stdio.h}
  2312. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2313. This is the equivalent of @code{sprintf} with the variable argument list
  2314. specified directly as for @code{vprintf}.
  2315. @end deftypefun
  2316. @deftypefun int vswprintf (wchar_t *@var{ws}, size_t @var{size}, const wchar_t *@var{template}, va_list @var{ap})
  2317. @standards{GNU, wchar.h}
  2318. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2319. This is the equivalent of @code{swprintf} with the variable argument list
  2320. specified directly as for @code{vwprintf}.
  2321. @end deftypefun
  2322. @deftypefun int vsnprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, va_list @var{ap})
  2323. @standards{GNU, stdio.h}
  2324. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2325. This is the equivalent of @code{snprintf} with the variable argument list
  2326. specified directly as for @code{vprintf}.
  2327. @end deftypefun
  2328. @deftypefun int vasprintf (char **@var{ptr}, const char *@var{template}, va_list @var{ap})
  2329. @standards{GNU, stdio.h}
  2330. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2331. The @code{vasprintf} function is the equivalent of @code{asprintf} with the
  2332. variable argument list specified directly as for @code{vprintf}.
  2333. @end deftypefun
  2334. @deftypefun int obstack_vprintf (struct obstack *@var{obstack}, const char *@var{template}, va_list @var{ap})
  2335. @standards{GNU, stdio.h}
  2336. @safety{@prelim{}@mtsafe{@mtsrace{:obstack} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
  2337. @c The obstack is not guarded by mutexes, it might be at an inconsistent
  2338. @c state within a signal handler, and it could be left at an
  2339. @c inconsistent state in case of cancellation.
  2340. The @code{obstack_vprintf} function is the equivalent of
  2341. @code{obstack_printf} with the variable argument list specified directly
  2342. as for @code{vprintf}.
  2343. @end deftypefun
  2344. @deftypefun int vdprintf (int @var{fd}, const char *@var{template}, va_list @var{ap})
  2345. @standards{POSIX, stdio.h}
  2346. @safety{@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  2347. The @code{vdprintf} is the equivalent of @code{dprintf}, but processes
  2348. an argument list.
  2349. @end deftypefun
  2350. Here's an example showing how you might use @code{vfprintf}. This is a
  2351. function that prints error messages to the stream @code{stderr}, along
  2352. with a prefix indicating the name of the program
  2353. (@pxref{Error Messages}, for a description of
  2354. @code{program_invocation_short_name}).
  2355. @smallexample
  2356. @group
  2357. #include <stdio.h>
  2358. #include <stdarg.h>
  2359. void
  2360. eprintf (const char *template, ...)
  2361. @{
  2362. va_list ap;
  2363. extern char *program_invocation_short_name;
  2364. fprintf (stderr, "%s: ", program_invocation_short_name);
  2365. va_start (ap, template);
  2366. vfprintf (stderr, template, ap);
  2367. va_end (ap);
  2368. @}
  2369. @end group
  2370. @end smallexample
  2371. @noindent
  2372. You could call @code{eprintf} like this:
  2373. @smallexample
  2374. eprintf ("file `%s' does not exist\n", filename);
  2375. @end smallexample
  2376. In GNU C, there is a special construct you can use to let the compiler
  2377. know that a function uses a @code{printf}-style format string. Then it
  2378. can check the number and types of arguments in each call to the
  2379. function, and warn you when they do not match the format string.
  2380. For example, take this declaration of @code{eprintf}:
  2381. @smallexample
  2382. void eprintf (const char *template, ...)
  2383. __attribute__ ((format (printf, 1, 2)));
  2384. @end smallexample
  2385. @noindent
  2386. This tells the compiler that @code{eprintf} uses a format string like
  2387. @code{printf} (as opposed to @code{scanf}; @pxref{Formatted Input});
  2388. the format string appears as the first argument;
  2389. and the arguments to satisfy the format begin with the second.
  2390. @xref{Function Attributes, , Declaring Attributes of Functions,
  2391. gcc, Using GNU CC}, for more information.
  2392. @node Parsing a Template String
  2393. @subsection Parsing a Template String
  2394. @cindex parsing a template string
  2395. You can use the function @code{parse_printf_format} to obtain
  2396. information about the number and types of arguments that are expected by
  2397. a given template string. This function permits interpreters that
  2398. provide interfaces to @code{printf} to avoid passing along invalid
  2399. arguments from the user's program, which could cause a crash.
  2400. All the symbols described in this section are declared in the header
  2401. file @file{printf.h}.
  2402. @deftypefun size_t parse_printf_format (const char *@var{template}, size_t @var{n}, int *@var{argtypes})
  2403. @standards{GNU, printf.h}
  2404. @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
  2405. This function returns information about the number and types of
  2406. arguments expected by the @code{printf} template string @var{template}.
  2407. The information is stored in the array @var{argtypes}; each element of
  2408. this array describes one argument. This information is encoded using
  2409. the various @samp{PA_} macros, listed below.
  2410. The argument @var{n} specifies the number of elements in the array
  2411. @var{argtypes}. This is the maximum number of elements that
  2412. @code{parse_printf_format} will try to write.
  2413. @code{parse_printf_format} returns the total number of arguments required
  2414. by @var{template}. If this number is greater than @var{n}, then the
  2415. information returned describes only the first @var{n} arguments. If you
  2416. want information about additional arguments, allocate a bigger
  2417. array and call @code{parse_printf_format} again.
  2418. @end deftypefun
  2419. The argument types are encoded as a combination of a basic type and
  2420. modifier flag bits.
  2421. @deftypevr Macro int PA_FLAG_MASK
  2422. @standards{GNU, printf.h}
  2423. This macro is a bitmask for the type modifier flag bits. You can write
  2424. the expression @code{(argtypes[i] & PA_FLAG_MASK)} to extract just the
  2425. flag bits for an argument, or @code{(argtypes[i] & ~PA_FLAG_MASK)} to
  2426. extract just the basic type code.
  2427. @end deftypevr
  2428. Here are symbolic constants that represent the basic types; they stand
  2429. for integer values.
  2430. @vtable @code
  2431. @item PA_INT
  2432. @standards{GNU, printf.h}
  2433. This specifies that the base type is @code{int}.
  2434. @item PA_CHAR
  2435. @standards{GNU, printf.h}
  2436. This specifies that the base type is @code{int}, cast to @code{char}.
  2437. @item PA_STRING
  2438. @standards{GNU, printf.h}
  2439. This specifies that the base type is @code{char *}, a null-terminated string.
  2440. @item PA_POINTER
  2441. @standards{GNU, printf.h}
  2442. This specifies that the base type is @code{void *}, an arbitrary pointer.
  2443. @item PA_FLOAT
  2444. @standards{GNU, printf.h}
  2445. This specifies that the base type is @code{float}.
  2446. @item PA_DOUBLE
  2447. @standards{GNU, printf.h}
  2448. This specifies that the base type is @code{double}.
  2449. @item PA_LAST
  2450. @standards{GNU, printf.h}
  2451. You can define additional base types for your own programs as offsets
  2452. from @code{PA_LAST}. For example, if you have data types @samp{foo}
  2453. and @samp{bar} with their own specialized @code{printf} conversions,
  2454. you could define encodings for these types as:
  2455. @smallexample
  2456. #define PA_FOO PA_LAST
  2457. #define PA_BAR (PA_LAST + 1)
  2458. @end smallexample
  2459. @end vtable
  2460. Here are the flag bits that modify a basic type. They are combined with
  2461. the code for the basic type using inclusive-or.
  2462. @vtable @code
  2463. @item PA_FLAG_PTR
  2464. @standards{GNU, printf.h}
  2465. If this bit is set, it indicates that the encoded type is a pointer to
  2466. the base type, rather than an immediate value.
  2467. For example, @samp{PA_INT|PA_FLAG_PTR} represents the type @samp{int *}.
  2468. @item PA_FLAG_SHORT
  2469. @standards{GNU, printf.h}
  2470. If this bit is set, it indicates that the base type is modified with
  2471. @code{short}. (This corresponds to the @samp{h} type modifier.)
  2472. @item PA_FLAG_LONG
  2473. @standards{GNU, printf.h}
  2474. If this bit is set, it indicates that the base type is modified with
  2475. @code{long}. (This corresponds to the @samp{l} type modifier.)
  2476. @item PA_FLAG_LONG_LONG
  2477. @standards{GNU, printf.h}
  2478. If this bit is set, it indicates that the base type is modified with
  2479. @code{long long}. (This corresponds to the @samp{L} type modifier.)
  2480. @item PA_FLAG_LONG_DOUBLE
  2481. @standards{GNU, printf.h}
  2482. This is a synonym for @code{PA_FLAG_LONG_LONG}, used by convention with
  2483. a base type of @code{PA_DOUBLE} to indicate a type of @code{long double}.
  2484. @end vtable
  2485. @ifinfo
  2486. For an example of using these facilities, see @ref{Example of Parsing}.
  2487. @end ifinfo
  2488. @node Example of Parsing
  2489. @subsection Example of Parsing a Template String
  2490. Here is an example of decoding argument types for a format string. We
  2491. assume this is part of an interpreter which contains arguments of type
  2492. @code{NUMBER}, @code{CHAR}, @code{STRING} and @code{STRUCTURE} (and
  2493. perhaps others which are not valid here).
  2494. @smallexample
  2495. /* @r{Test whether the @var{nargs} specified objects}
  2496. @r{in the vector @var{args} are valid}
  2497. @r{for the format string @var{format}:}
  2498. @r{if so, return 1.}
  2499. @r{If not, return 0 after printing an error message.} */
  2500. int
  2501. validate_args (char *format, int nargs, OBJECT *args)
  2502. @{
  2503. int *argtypes;
  2504. int nwanted;
  2505. /* @r{Get the information about the arguments.}
  2506. @r{Each conversion specification must be at least two characters}
  2507. @r{long, so there cannot be more specifications than half the}
  2508. @r{length of the string.} */
  2509. argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int));
  2510. nwanted = parse_printf_format (format, nargs, argtypes);
  2511. /* @r{Check the number of arguments.} */
  2512. if (nwanted > nargs)
  2513. @{
  2514. error ("too few arguments (at least %d required)", nwanted);
  2515. return 0;
  2516. @}
  2517. /* @r{Check the C type wanted for each argument}
  2518. @r{and see if the object given is suitable.} */
  2519. for (i = 0; i < nwanted; i++)
  2520. @{
  2521. int wanted;
  2522. if (argtypes[i] & PA_FLAG_PTR)
  2523. wanted = STRUCTURE;
  2524. else
  2525. switch (argtypes[i] & ~PA_FLAG_MASK)
  2526. @{
  2527. case PA_INT:
  2528. case PA_FLOAT:
  2529. case PA_DOUBLE:
  2530. wanted = NUMBER;
  2531. break;
  2532. case PA_CHAR:
  2533. wanted = CHAR;
  2534. break;
  2535. case PA_STRING:
  2536. wanted = STRING;
  2537. break;
  2538. case PA_POINTER:
  2539. wanted = STRUCTURE;
  2540. break;
  2541. @}
  2542. if (TYPE (args[i]) != wanted)
  2543. @{
  2544. error ("type mismatch for arg number %d", i);
  2545. return 0;
  2546. @}
  2547. @}
  2548. return 1;
  2549. @}
  2550. @end smallexample
  2551. @node Customizing Printf
  2552. @section Customizing @code{printf}
  2553. @cindex customizing @code{printf}
  2554. @cindex defining new @code{printf} conversions
  2555. @cindex extending @code{printf}
  2556. @Theglibc{} lets you define your own custom conversion specifiers
  2557. for @code{printf} template strings, to teach @code{printf} clever ways
  2558. to print the important data structures of your program.
  2559. The way you do this is by registering the conversion with the function
  2560. @code{register_printf_function}; see @ref{Registering New Conversions}.
  2561. One of the arguments you pass to this function is a pointer to a handler
  2562. function that produces the actual output; see @ref{Defining the Output
  2563. Handler}, for information on how to write this function.
  2564. You can also install a function that just returns information about the
  2565. number and type of arguments expected by the conversion specifier.
  2566. @xref{Parsing a Template String}, for information about this.
  2567. The facilities of this section are declared in the header file
  2568. @file{printf.h}.
  2569. @menu
  2570. * Registering New Conversions:: Using @code{register_printf_function}
  2571. to register a new output conversion.
  2572. * Conversion Specifier Options:: The handler must be able to get
  2573. the options specified in the
  2574. template when it is called.
  2575. * Defining the Output Handler:: Defining the handler and arginfo
  2576. functions that are passed as arguments
  2577. to @code{register_printf_function}.
  2578. * Printf Extension Example:: How to define a @code{printf}
  2579. handler function.
  2580. * Predefined Printf Handlers:: Predefined @code{printf} handlers.
  2581. @end menu
  2582. @strong{Portability Note:} The ability to extend the syntax of
  2583. @code{printf} template strings is a GNU extension. ISO standard C has
  2584. nothing similar. When using the GNU C compiler or any other compiler
  2585. that interprets calls to standard I/O functions according to the rules
  2586. of the language standard it is necessary to disable such handling by
  2587. the appropriate compiler option. Otherwise the behavior of a program
  2588. that relies on the extension is undefined.
  2589. @node Registering New Conversions
  2590. @subsection Registering New Conversions
  2591. The function to register a new output conversion is
  2592. @code{register_printf_function}, declared in @file{printf.h}.
  2593. @pindex printf.h
  2594. @deftypefun int register_printf_function (int @var{spec}, printf_function @var{handler-function}, printf_arginfo_function @var{arginfo-function})
  2595. @standards{GNU, printf.h}
  2596. @safety{@prelim{}@mtunsafe{@mtasuconst{:printfext}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @aculock{}}}
  2597. @c This function is guarded by the global non-recursive libc lock, but
  2598. @c users of the variables it sets aren't, and those should be MT-Safe,
  2599. @c so we're ruling out the use of this extension with threads. Calling
  2600. @c it from a signal handler may self-deadlock, and cancellation may
  2601. @c leave the lock held, besides leaking allocated memory.
  2602. This function defines the conversion specifier character @var{spec}.
  2603. Thus, if @var{spec} is @code{'Y'}, it defines the conversion @samp{%Y}.
  2604. You can redefine the built-in conversions like @samp{%s}, but flag
  2605. characters like @samp{#} and type modifiers like @samp{l} can never be
  2606. used as conversions; calling @code{register_printf_function} for those
  2607. characters has no effect. It is advisable not to use lowercase letters,
  2608. since the ISO C standard warns that additional lowercase letters may be
  2609. standardized in future editions of the standard.
  2610. The @var{handler-function} is the function called by @code{printf} and
  2611. friends when this conversion appears in a template string.
  2612. @xref{Defining the Output Handler}, for information about how to define
  2613. a function to pass as this argument. If you specify a null pointer, any
  2614. existing handler function for @var{spec} is removed.
  2615. The @var{arginfo-function} is the function called by
  2616. @code{parse_printf_format} when this conversion appears in a
  2617. template string. @xref{Parsing a Template String}, for information
  2618. about this.
  2619. @c The following is not true anymore. The `parse_printf_format' function
  2620. @c is now also called from `vfprintf' via `parse_one_spec'.
  2621. @c --drepper@gnu, 1996/11/14
  2622. @c
  2623. @c Normally, you install both functions for a conversion at the same time,
  2624. @c but if you are never going to call @code{parse_printf_format}, you do
  2625. @c not need to define an arginfo function.
  2626. @strong{Attention:} In @theglibc{} versions before 2.0 the
  2627. @var{arginfo-function} function did not need to be installed unless
  2628. the user used the @code{parse_printf_format} function. This has changed.
  2629. Now a call to any of the @code{printf} functions will call this
  2630. function when this format specifier appears in the format string.
  2631. The return value is @code{0} on success, and @code{-1} on failure
  2632. (which occurs if @var{spec} is out of range).
  2633. @strong{Portability Note:} It is possible to redefine the standard output
  2634. conversions but doing so is strongly discouraged because it may interfere
  2635. with the behavior of programs and compiler implementations that assume
  2636. the effects of the conversions conform to the relevant language standards.
  2637. In addition, conforming compilers need not guarantee that the function
  2638. registered for a standard conversion will be called for each such
  2639. conversion in every format string in a program.
  2640. @end deftypefun
  2641. @node Conversion Specifier Options
  2642. @subsection Conversion Specifier Options
  2643. If you define a meaning for @samp{%A}, what if the template contains
  2644. @samp{%+23A} or @samp{%-#A}? To implement a sensible meaning for these,
  2645. the handler when called needs to be able to get the options specified in
  2646. the template.
  2647. Both the @var{handler-function} and @var{arginfo-function} accept an
  2648. argument that points to a @code{struct printf_info}, which contains
  2649. information about the options appearing in an instance of the conversion
  2650. specifier. This data type is declared in the header file
  2651. @file{printf.h}.
  2652. @pindex printf.h
  2653. @deftp {Type} {struct printf_info}
  2654. @standards{GNU, printf.h}
  2655. This structure is used to pass information about the options appearing
  2656. in an instance of a conversion specifier in a @code{printf} template
  2657. string to the handler and arginfo functions for that specifier. It
  2658. contains the following members:
  2659. @table @code
  2660. @item int prec
  2661. This is the precision specified. The value is @code{-1} if no precision
  2662. was specified. If the precision was given as @samp{*}, the
  2663. @code{printf_info} structure passed to the handler function contains the
  2664. actual value retrieved from the argument list. But the structure passed
  2665. to the arginfo function contains a value of @code{INT_MIN}, since the
  2666. actual value is not known.
  2667. @item int width
  2668. This is the minimum field width specified. The value is @code{0} if no
  2669. width was specified. If the field width was given as @samp{*}, the
  2670. @code{printf_info} structure passed to the handler function contains the
  2671. actual value retrieved from the argument list. But the structure passed
  2672. to the arginfo function contains a value of @code{INT_MIN}, since the
  2673. actual value is not known.
  2674. @item wchar_t spec
  2675. This is the conversion specifier character specified. It's stored in
  2676. the structure so that you can register the same handler function for
  2677. multiple characters, but still have a way to tell them apart when the
  2678. handler function is called.
  2679. @item unsigned int is_long_double
  2680. This is a boolean that is true if the @samp{L}, @samp{ll}, or @samp{q}
  2681. type modifier was specified. For integer conversions, this indicates
  2682. @code{long long int}, as opposed to @code{long double} for floating
  2683. point conversions.
  2684. @item unsigned int is_char
  2685. This is a boolean that is true if the @samp{hh} type modifier was specified.
  2686. @item unsigned int is_short
  2687. This is a boolean that is true if the @samp{h} type modifier was specified.
  2688. @item unsigned int is_long
  2689. This is a boolean that is true if the @samp{l} type modifier was specified.
  2690. @item unsigned int alt
  2691. This is a boolean that is true if the @samp{#} flag was specified.
  2692. @item unsigned int space
  2693. This is a boolean that is true if the @samp{ } flag was specified.
  2694. @item unsigned int left
  2695. This is a boolean that is true if the @samp{-} flag was specified.
  2696. @item unsigned int showsign
  2697. This is a boolean that is true if the @samp{+} flag was specified.
  2698. @item unsigned int group
  2699. This is a boolean that is true if the @samp{'} flag was specified.
  2700. @item unsigned int extra
  2701. This flag has a special meaning depending on the context. It could
  2702. be used freely by the user-defined handlers but when called from
  2703. the @code{printf} function this variable always contains the value
  2704. @code{0}.
  2705. @item unsigned int wide
  2706. This flag is set if the stream is wide oriented.
  2707. @item wchar_t pad
  2708. This is the character to use for padding the output to the minimum field
  2709. width. The value is @code{'0'} if the @samp{0} flag was specified, and
  2710. @code{' '} otherwise.
  2711. @end table
  2712. @end deftp
  2713. @node Defining the Output Handler
  2714. @subsection Defining the Output Handler
  2715. Now let's look at how to define the handler and arginfo functions
  2716. which are passed as arguments to @code{register_printf_function}.
  2717. @strong{Compatibility Note:} The interface changed in @theglibc{}
  2718. version 2.0. Previously the third argument was of type
  2719. @code{va_list *}.
  2720. You should define your handler functions with a prototype like:
  2721. @smallexample
  2722. int @var{function} (FILE *stream, const struct printf_info *info,
  2723. const void *const *args)
  2724. @end smallexample
  2725. The @var{stream} argument passed to the handler function is the stream to
  2726. which it should write output.
  2727. The @var{info} argument is a pointer to a structure that contains
  2728. information about the various options that were included with the
  2729. conversion in the template string. You should not modify this structure
  2730. inside your handler function. @xref{Conversion Specifier Options}, for
  2731. a description of this data structure.
  2732. @c The following changes some time back. --drepper@gnu, 1996/11/14
  2733. @c
  2734. @c The @code{ap_pointer} argument is used to pass the tail of the variable
  2735. @c argument list containing the values to be printed to your handler.
  2736. @c Unlike most other functions that can be passed an explicit variable
  2737. @c argument list, this is a @emph{pointer} to a @code{va_list}, rather than
  2738. @c the @code{va_list} itself. Thus, you should fetch arguments by
  2739. @c means of @code{va_arg (*ap_pointer, @var{type})}.
  2740. @c
  2741. @c (Passing a pointer here allows the function that calls your handler
  2742. @c function to update its own @code{va_list} variable to account for the
  2743. @c arguments that your handler processes. @xref{Variadic Functions}.)
  2744. The @var{args} is a vector of pointers to the arguments data.
  2745. The number of arguments was determined by calling the argument
  2746. information function provided by the user.
  2747. Your handler function should return a value just like @code{printf}
  2748. does: it should return the number of characters it has written, or a
  2749. negative value to indicate an error.
  2750. @deftp {Data Type} printf_function
  2751. @standards{GNU, printf.h}
  2752. This is the data type that a handler function should have.
  2753. @end deftp
  2754. If you are going to use @w{@code{parse_printf_format}} in your
  2755. application, you must also define a function to pass as the
  2756. @var{arginfo-function} argument for each new conversion you install with
  2757. @code{register_printf_function}.
  2758. You have to define these functions with a prototype like:
  2759. @smallexample
  2760. int @var{function} (const struct printf_info *info,
  2761. size_t n, int *argtypes)
  2762. @end smallexample
  2763. The return value from the function should be the number of arguments the
  2764. conversion expects. The function should also fill in no more than
  2765. @var{n} elements of the @var{argtypes} array with information about the
  2766. types of each of these arguments. This information is encoded using the
  2767. various @samp{PA_} macros. (You will notice that this is the same
  2768. calling convention @code{parse_printf_format} itself uses.)
  2769. @deftp {Data Type} printf_arginfo_function
  2770. @standards{GNU, printf.h}
  2771. This type is used to describe functions that return information about
  2772. the number and type of arguments used by a conversion specifier.
  2773. @end deftp
  2774. @node Printf Extension Example
  2775. @subsection @code{printf} Extension Example
  2776. Here is an example showing how to define a @code{printf} handler function.
  2777. This program defines a data structure called a @code{Widget} and
  2778. defines the @samp{%W} conversion to print information about @w{@code{Widget *}}
  2779. arguments, including the pointer value and the name stored in the data
  2780. structure. The @samp{%W} conversion supports the minimum field width and
  2781. left-justification options, but ignores everything else.
  2782. @smallexample
  2783. @include rprintf.c.texi
  2784. @end smallexample
  2785. The output produced by this program looks like:
  2786. @smallexample
  2787. |<Widget 0xffeffb7c: mywidget>|
  2788. | <Widget 0xffeffb7c: mywidget>|
  2789. |<Widget 0xffeffb7c: mywidget> |
  2790. @end smallexample
  2791. @node Predefined Printf Handlers
  2792. @subsection Predefined @code{printf} Handlers
  2793. @Theglibc{} also contains a concrete and useful application of the
  2794. @code{printf} handler extension. There are two functions available
  2795. which implement a special way to print floating-point numbers.
  2796. @deftypefun int printf_size (FILE *@var{fp}, const struct printf_info *@var{info}, const void *const *@var{args})
  2797. @standards{GNU, printf.h}
  2798. @safety{@prelim{}@mtsafe{@mtsrace{:fp} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @acucorrupt{}}}
  2799. @c This is meant to be called by vfprintf, that should hold the lock on
  2800. @c the stream, but if this function is called directly, output will be
  2801. @c racy, besides the uses of the global locale object while other
  2802. @c threads may be changing it and the possbility of leaving the stream
  2803. @c object in an inconsistent state in case of cancellation.
  2804. Print a given floating point number as for the format @code{%f} except
  2805. that there is a postfix character indicating the divisor for the
  2806. number to make this less than 1000. There are two possible divisors:
  2807. powers of 1024 or powers of 1000. Which one is used depends on the
  2808. format character specified while registered this handler. If the
  2809. character is of lower case, 1024 is used. For upper case characters,
  2810. 1000 is used.
  2811. The postfix tag corresponds to bytes, kilobytes, megabytes, gigabytes,
  2812. etc. The full table is:
  2813. @ifinfo
  2814. @multitable {' '} {2^10 (1024)} {zetta} {Upper} {10^24 (1000)}
  2815. @item low @tab Multiplier @tab From @tab Upper @tab Multiplier
  2816. @item ' ' @tab 1 @tab @tab ' ' @tab 1
  2817. @item k @tab 2^10 (1024) @tab kilo @tab K @tab 10^3 (1000)
  2818. @item m @tab 2^20 @tab mega @tab M @tab 10^6
  2819. @item g @tab 2^30 @tab giga @tab G @tab 10^9
  2820. @item t @tab 2^40 @tab tera @tab T @tab 10^12
  2821. @item p @tab 2^50 @tab peta @tab P @tab 10^15
  2822. @item e @tab 2^60 @tab exa @tab E @tab 10^18
  2823. @item z @tab 2^70 @tab zetta @tab Z @tab 10^21
  2824. @item y @tab 2^80 @tab yotta @tab Y @tab 10^24
  2825. @end multitable
  2826. @end ifinfo
  2827. @iftex
  2828. @tex
  2829. \hbox to\hsize{\hfil\vbox{\offinterlineskip
  2830. \hrule
  2831. \halign{\strut#& \vrule#\tabskip=1em plus2em& {\tt#}\hfil& \vrule#& #\hfil& \vrule#& #\hfil& \vrule#& {\tt#}\hfil& \vrule#& #\hfil& \vrule#\tabskip=0pt\cr
  2832. \noalign{\hrule}
  2833. \omit&height2pt&\omit&&\omit&&\omit&&\omit&&\omit&\cr
  2834. && \omit low && Multiplier && From && \omit Upper && Multiplier &\cr
  2835. \omit&height2pt&\omit&&\omit&&\omit&&\omit&&\omit&\cr
  2836. \noalign{\hrule}
  2837. && {\tt\char32} && 1 && && {\tt\char32} && 1 &\cr
  2838. && k && $2^{10} = 1024$ && kilo && K && $10^3 = 1000$ &\cr
  2839. && m && $2^{20}$ && mega && M && $10^6$ &\cr
  2840. && g && $2^{30}$ && giga && G && $10^9$ &\cr
  2841. && t && $2^{40}$ && tera && T && $10^{12}$ &\cr
  2842. && p && $2^{50}$ && peta && P && $10^{15}$ &\cr
  2843. && e && $2^{60}$ && exa && E && $10^{18}$ &\cr
  2844. && z && $2^{70}$ && zetta && Z && $10^{21}$ &\cr
  2845. && y && $2^{80}$ && yotta && Y && $10^{24}$ &\cr
  2846. \noalign{\hrule}}}\hfil}
  2847. @end tex
  2848. @end iftex
  2849. The default precision is 3, i.e., 1024 is printed with a lower-case
  2850. format character as if it were @code{%.3fk} and will yield @code{1.000k}.
  2851. @end deftypefun
  2852. Due to the requirements of @code{register_printf_function} we must also
  2853. provide the function which returns information about the arguments.
  2854. @deftypefun int printf_size_info (const struct printf_info *@var{info}, size_t @var{n}, int *@var{argtypes})
  2855. @standards{GNU, printf.h}
  2856. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  2857. This function will return in @var{argtypes} the information about the
  2858. used parameters in the way the @code{vfprintf} implementation expects
  2859. it. The format always takes one argument.
  2860. @end deftypefun
  2861. To use these functions both functions must be registered with a call like
  2862. @smallexample
  2863. register_printf_function ('B', printf_size, printf_size_info);
  2864. @end smallexample
  2865. Here we register the functions to print numbers as powers of 1000 since
  2866. the format character @code{'B'} is an upper-case character. If we
  2867. would additionally use @code{'b'} in a line like
  2868. @smallexample
  2869. register_printf_function ('b', printf_size, printf_size_info);
  2870. @end smallexample
  2871. @noindent
  2872. we could also print using a power of 1024. Please note that all that is
  2873. different in these two lines is the format specifier. The
  2874. @code{printf_size} function knows about the difference between lower and upper
  2875. case format specifiers.
  2876. The use of @code{'B'} and @code{'b'} is no coincidence. Rather it is
  2877. the preferred way to use this functionality since it is available on
  2878. some other systems which also use format specifiers.
  2879. @node Formatted Input
  2880. @section Formatted Input
  2881. @cindex formatted input from a stream
  2882. @cindex reading from a stream, formatted
  2883. @cindex format string, for @code{scanf}
  2884. @cindex template, for @code{scanf}
  2885. The functions described in this section (@code{scanf} and related
  2886. functions) provide facilities for formatted input analogous to the
  2887. formatted output facilities. These functions provide a mechanism for
  2888. reading arbitrary values under the control of a @dfn{format string} or
  2889. @dfn{template string}.
  2890. @menu
  2891. * Formatted Input Basics:: Some basics to get you started.
  2892. * Input Conversion Syntax:: Syntax of conversion specifications.
  2893. * Table of Input Conversions:: Summary of input conversions and what they do.
  2894. * Numeric Input Conversions:: Details of conversions for reading numbers.
  2895. * String Input Conversions:: Details of conversions for reading strings.
  2896. * Dynamic String Input:: String conversions that @code{malloc} the buffer.
  2897. * Other Input Conversions:: Details of miscellaneous other conversions.
  2898. * Formatted Input Functions:: Descriptions of the actual functions.
  2899. * Variable Arguments Input:: @code{vscanf} and friends.
  2900. @end menu
  2901. @node Formatted Input Basics
  2902. @subsection Formatted Input Basics
  2903. Calls to @code{scanf} are superficially similar to calls to
  2904. @code{printf} in that arbitrary arguments are read under the control of
  2905. a template string. While the syntax of the conversion specifications in
  2906. the template is very similar to that for @code{printf}, the
  2907. interpretation of the template is oriented more towards free-format
  2908. input and simple pattern matching, rather than fixed-field formatting.
  2909. For example, most @code{scanf} conversions skip over any amount of
  2910. ``white space'' (including spaces, tabs, and newlines) in the input
  2911. file, and there is no concept of precision for the numeric input
  2912. conversions as there is for the corresponding output conversions.
  2913. Ordinarily, non-whitespace characters in the template are expected to
  2914. match characters in the input stream exactly, but a matching failure is
  2915. distinct from an input error on the stream.
  2916. @cindex conversion specifications (@code{scanf})
  2917. Another area of difference between @code{scanf} and @code{printf} is
  2918. that you must remember to supply pointers rather than immediate values
  2919. as the optional arguments to @code{scanf}; the values that are read are
  2920. stored in the objects that the pointers point to. Even experienced
  2921. programmers tend to forget this occasionally, so if your program is
  2922. getting strange errors that seem to be related to @code{scanf}, you
  2923. might want to double-check this.
  2924. When a @dfn{matching failure} occurs, @code{scanf} returns immediately,
  2925. leaving the first non-matching character as the next character to be
  2926. read from the stream. The normal return value from @code{scanf} is the
  2927. number of values that were assigned, so you can use this to determine if
  2928. a matching error happened before all the expected values were read.
  2929. @cindex matching failure, in @code{scanf}
  2930. The @code{scanf} function is typically used for things like reading in
  2931. the contents of tables. For example, here is a function that uses
  2932. @code{scanf} to initialize an array of @code{double}:
  2933. @smallexample
  2934. void
  2935. readarray (double *array, int n)
  2936. @{
  2937. int i;
  2938. for (i=0; i<n; i++)
  2939. if (scanf (" %lf", &(array[i])) != 1)
  2940. invalid_input_error ();
  2941. @}
  2942. @end smallexample
  2943. The formatted input functions are not used as frequently as the
  2944. formatted output functions. Partly, this is because it takes some care
  2945. to use them properly. Another reason is that it is difficult to recover
  2946. from a matching error.
  2947. If you are trying to read input that doesn't match a single, fixed
  2948. pattern, you may be better off using a tool such as Flex to generate a
  2949. lexical scanner, or Bison to generate a parser, rather than using
  2950. @code{scanf}. For more information about these tools, see @ref{Top, , ,
  2951. flex, Flex: The Lexical Scanner Generator}, and @ref{Top, , , bison, The
  2952. Bison Reference Manual}.
  2953. @node Input Conversion Syntax
  2954. @subsection Input Conversion Syntax
  2955. A @code{scanf} template string is a string that contains ordinary
  2956. multibyte characters interspersed with conversion specifications that
  2957. start with @samp{%}.
  2958. Any whitespace character (as defined by the @code{isspace} function;
  2959. @pxref{Classification of Characters}) in the template causes any number
  2960. of whitespace characters in the input stream to be read and discarded.
  2961. The whitespace characters that are matched need not be exactly the same
  2962. whitespace characters that appear in the template string. For example,
  2963. write @samp{ , } in the template to recognize a comma with optional
  2964. whitespace before and after.
  2965. Other characters in the template string that are not part of conversion
  2966. specifications must match characters in the input stream exactly; if
  2967. this is not the case, a matching failure occurs.
  2968. The conversion specifications in a @code{scanf} template string
  2969. have the general form:
  2970. @smallexample
  2971. % @var{flags} @var{width} @var{type} @var{conversion}
  2972. @end smallexample
  2973. In more detail, an input conversion specification consists of an initial
  2974. @samp{%} character followed in sequence by:
  2975. @itemize @bullet
  2976. @item
  2977. An optional @dfn{flag character} @samp{*}, which says to ignore the text
  2978. read for this specification. When @code{scanf} finds a conversion
  2979. specification that uses this flag, it reads input as directed by the
  2980. rest of the conversion specification, but it discards this input, does
  2981. not use a pointer argument, and does not increment the count of
  2982. successful assignments.
  2983. @cindex flag character (@code{scanf})
  2984. @item
  2985. An optional flag character @samp{a} (valid with string conversions only)
  2986. which requests allocation of a buffer long enough to store the string in.
  2987. (This is a GNU extension.)
  2988. @xref{Dynamic String Input}.
  2989. @item
  2990. An optional decimal integer that specifies the @dfn{maximum field
  2991. width}. Reading of characters from the input stream stops either when
  2992. this maximum is reached or when a non-matching character is found,
  2993. whichever happens first. Most conversions discard initial whitespace
  2994. characters (those that don't are explicitly documented), and these
  2995. discarded characters don't count towards the maximum field width.
  2996. String input conversions store a null character to mark the end of the
  2997. input; the maximum field width does not include this terminator.
  2998. @cindex maximum field width (@code{scanf})
  2999. @item
  3000. An optional @dfn{type modifier character}. For example, you can
  3001. specify a type modifier of @samp{l} with integer conversions such as
  3002. @samp{%d} to specify that the argument is a pointer to a @code{long int}
  3003. rather than a pointer to an @code{int}.
  3004. @cindex type modifier character (@code{scanf})
  3005. @item
  3006. A character that specifies the conversion to be applied.
  3007. @end itemize
  3008. The exact options that are permitted and how they are interpreted vary
  3009. between the different conversion specifiers. See the descriptions of the
  3010. individual conversions for information about the particular options that
  3011. they allow.
  3012. With the @samp{-Wformat} option, the GNU C compiler checks calls to
  3013. @code{scanf} and related functions. It examines the format string and
  3014. verifies that the correct number and types of arguments are supplied.
  3015. There is also a GNU C syntax to tell the compiler that a function you
  3016. write uses a @code{scanf}-style format string.
  3017. @xref{Function Attributes, , Declaring Attributes of Functions,
  3018. gcc, Using GNU CC}, for more information.
  3019. @node Table of Input Conversions
  3020. @subsection Table of Input Conversions
  3021. @cindex input conversions, for @code{scanf}
  3022. Here is a table that summarizes the various conversion specifications:
  3023. @table @asis
  3024. @item @samp{%d}
  3025. Matches an optionally signed integer written in decimal. @xref{Numeric
  3026. Input Conversions}.
  3027. @item @samp{%i}
  3028. Matches an optionally signed integer in any of the formats that the C
  3029. language defines for specifying an integer constant. @xref{Numeric
  3030. Input Conversions}.
  3031. @item @samp{%b}
  3032. Matches an unsigned integer written in binary radix. This is an ISO
  3033. C23 feature. @xref{Numeric Input Conversions}.
  3034. @item @samp{%o}
  3035. Matches an unsigned integer written in octal radix.
  3036. @xref{Numeric Input Conversions}.
  3037. @item @samp{%u}
  3038. Matches an unsigned integer written in decimal radix.
  3039. @xref{Numeric Input Conversions}.
  3040. @item @samp{%x}, @samp{%X}
  3041. Matches an unsigned integer written in hexadecimal radix.
  3042. @xref{Numeric Input Conversions}.
  3043. @item @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, @samp{%F}, @samp{%G}
  3044. Matches an optionally signed floating-point number. @xref{Numeric Input
  3045. Conversions}.
  3046. @item @samp{%s}
  3047. Matches a string containing only non-whitespace characters.
  3048. @xref{String Input Conversions}. The presence of the @samp{l} modifier
  3049. determines whether the output is stored as a wide character string or a
  3050. multibyte string. If @samp{%s} is used in a wide character function the
  3051. string is converted as with multiple calls to @code{wcrtomb} into a
  3052. multibyte string. This means that the buffer must provide room for
  3053. @code{MB_CUR_MAX} bytes for each wide character read. In case
  3054. @samp{%ls} is used in a multibyte function the result is converted into
  3055. wide characters as with multiple calls of @code{mbrtowc} before being
  3056. stored in the user provided buffer.
  3057. @item @samp{%S}
  3058. This is an alias for @samp{%ls} which is supported for compatibility
  3059. with the Unix standard.
  3060. @item @samp{%[}
  3061. Matches a string of characters that belong to a specified set.
  3062. @xref{String Input Conversions}. The presence of the @samp{l} modifier
  3063. determines whether the output is stored as a wide character string or a
  3064. multibyte string. If @samp{%[} is used in a wide character function the
  3065. string is converted as with multiple calls to @code{wcrtomb} into a
  3066. multibyte string. This means that the buffer must provide room for
  3067. @code{MB_CUR_MAX} bytes for each wide character read. In case
  3068. @samp{%l[} is used in a multibyte function the result is converted into
  3069. wide characters as with multiple calls of @code{mbrtowc} before being
  3070. stored in the user provided buffer.
  3071. @item @samp{%c}
  3072. Matches a string of one or more characters; the number of characters
  3073. read is controlled by the maximum field width given for the conversion.
  3074. @xref{String Input Conversions}.
  3075. If @samp{%c} is used in a wide stream function the read value is
  3076. converted from a wide character to the corresponding multibyte character
  3077. before storing it. Note that this conversion can produce more than one
  3078. byte of output and therefore the provided buffer must be large enough for up
  3079. to @code{MB_CUR_MAX} bytes for each character. If @samp{%lc} is used in
  3080. a multibyte function the input is treated as a multibyte sequence (and
  3081. not bytes) and the result is converted as with calls to @code{mbrtowc}.
  3082. @item @samp{%C}
  3083. This is an alias for @samp{%lc} which is supported for compatibility
  3084. with the Unix standard.
  3085. @item @samp{%p}
  3086. Matches a pointer value in the same implementation-defined format used
  3087. by the @samp{%p} output conversion for @code{printf}. @xref{Other Input
  3088. Conversions}.
  3089. @item @samp{%n}
  3090. This conversion doesn't read any characters; it records the number of
  3091. characters read so far by this call. @xref{Other Input Conversions}.
  3092. @item @samp{%%}
  3093. This matches a literal @samp{%} character in the input stream. No
  3094. corresponding argument is used. @xref{Other Input Conversions}.
  3095. @end table
  3096. If the syntax of a conversion specification is invalid, the behavior is
  3097. undefined. If there aren't enough function arguments provided to supply
  3098. addresses for all the conversion specifications in the template strings
  3099. that perform assignments, or if the arguments are not of the correct
  3100. types, the behavior is also undefined. On the other hand, extra
  3101. arguments are simply ignored.
  3102. @node Numeric Input Conversions
  3103. @subsection Numeric Input Conversions
  3104. This section describes the @code{scanf} conversions for reading numeric
  3105. values.
  3106. The @samp{%d} conversion matches an optionally signed integer in decimal
  3107. radix. The syntax that is recognized is the same as that for the
  3108. @code{strtol} function (@pxref{Parsing of Integers}) with the value
  3109. @code{10} for the @var{base} argument.
  3110. The @samp{%i} conversion matches an optionally signed integer in any of
  3111. the formats that the C language defines for specifying an integer
  3112. constant. The syntax that is recognized is the same as that for the
  3113. @code{strtol} function (@pxref{Parsing of Integers}) with the value
  3114. @code{0} for the @var{base} argument. (You can print integers in this
  3115. syntax with @code{printf} by using the @samp{#} flag character with the
  3116. @samp{%x}, @samp{%o}, @samp{%b}, or @samp{%d} conversion.
  3117. @xref{Integer Conversions}.)
  3118. For example, any of the strings @samp{10}, @samp{0xa}, or @samp{012}
  3119. could be read in as integers under the @samp{%i} conversion. Each of
  3120. these specifies a number with decimal value @code{10}.
  3121. The @samp{%b}, @samp{%o}, @samp{%u}, and @samp{%x} conversions match unsigned
  3122. integers in binary, octal, decimal, and hexadecimal radices, respectively. The
  3123. syntax that is recognized is the same as that for the @code{strtoul}
  3124. function (@pxref{Parsing of Integers}) with the appropriate value
  3125. (@code{2}, @code{8}, @code{10}, or @code{16}) for the @var{base}
  3126. argument. The @samp{%b} conversion accepts an optional leading
  3127. @samp{0b} or @samp{0B} in all standards modes.
  3128. The @samp{%X} conversion is identical to the @samp{%x} conversion. They
  3129. both permit either uppercase or lowercase letters to be used as digits.
  3130. The default type of the corresponding argument for the @code{%d},
  3131. @code{%i}, and @code{%n} conversions is @code{int *}, and
  3132. @code{unsigned int *} for the other integer conversions. You can use
  3133. the following type modifiers to specify other sizes of integer:
  3134. @table @samp
  3135. @item hh
  3136. Specifies that the argument is a @code{signed char *} or @code{unsigned
  3137. char *}.
  3138. This modifier was introduced in @w{ISO C99}.
  3139. @item h
  3140. Specifies that the argument is a @code{short int *} or @code{unsigned
  3141. short int *}.
  3142. @item j
  3143. Specifies that the argument is a @code{intmax_t *} or @code{uintmax_t *}.
  3144. This modifier was introduced in @w{ISO C99}.
  3145. @item l
  3146. Specifies that the argument is a @code{long int *} or @code{unsigned
  3147. long int *}. Two @samp{l} characters is like the @samp{L} modifier, below.
  3148. If used with @samp{%c} or @samp{%s} the corresponding parameter is
  3149. considered as a pointer to a wide character or wide character string
  3150. respectively. This use of @samp{l} was introduced in @w{Amendment 1} to
  3151. @w{ISO C90}.
  3152. @need 100
  3153. @item ll
  3154. @itemx L
  3155. @itemx q
  3156. Specifies that the argument is a @code{long long int *} or @code{unsigned long long int *}. (The @code{long long} type is an extension supported by the
  3157. GNU C compiler. For systems that don't provide extra-long integers, this
  3158. is the same as @code{long int}.)
  3159. The @samp{q} modifier is another name for the same thing, which comes
  3160. from 4.4 BSD; a @w{@code{long long int}} is sometimes called a ``quad''
  3161. @code{int}.
  3162. @item t
  3163. Specifies that the argument is a @code{ptrdiff_t *}.
  3164. This modifier was introduced in @w{ISO C99}.
  3165. @item w@var{n}
  3166. Specifies that the argument is an @code{int@var{n}_t *} or
  3167. @code{int_least@var{n}_t *} (which are the same type), or
  3168. @code{uint@var{n}_t *} or @code{uint_least@var{n}_t *} (which are the
  3169. same type).
  3170. This modifier was introduced in @w{ISO C23}.
  3171. @item wf@var{n}
  3172. Specifies that the argument is an @code{int_fast@var{n}_t *} or
  3173. @code{uint_fast@var{n}_t *}.
  3174. This modifier was introduced in @w{ISO C23}.
  3175. @item z
  3176. Specifies that the argument is a @code{size_t *}.
  3177. This modifier was introduced in @w{ISO C99}.
  3178. @end table
  3179. All of the @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, @samp{%F} and @samp{%G}
  3180. input conversions are interchangeable. They all match an optionally
  3181. signed floating point number, in the same syntax as for the
  3182. @code{strtod} function (@pxref{Parsing of Floats}).
  3183. For the floating-point input conversions, the default argument type is
  3184. @code{float *}. (This is different from the corresponding output
  3185. conversions, where the default type is @code{double}; remember that
  3186. @code{float} arguments to @code{printf} are converted to @code{double}
  3187. by the default argument promotions, but @code{float *} arguments are
  3188. not promoted to @code{double *}.) You can specify other sizes of float
  3189. using these type modifiers:
  3190. @table @samp
  3191. @item l
  3192. Specifies that the argument is of type @code{double *}.
  3193. @item L
  3194. Specifies that the argument is of type @code{long double *}.
  3195. @end table
  3196. For all the above number parsing formats there is an additional optional
  3197. flag @samp{'}. When this flag is given the @code{scanf} function
  3198. expects the number represented in the input string to be formatted
  3199. according to the grouping rules of the currently selected locale
  3200. (@pxref{General Numeric}).
  3201. If the @code{"C"} or @code{"POSIX"} locale is selected there is no
  3202. difference. But for a locale which specifies values for the appropriate
  3203. fields in the locale the input must have the correct form in the input.
  3204. Otherwise the longest prefix with a correct form is processed.
  3205. @node String Input Conversions
  3206. @subsection String Input Conversions
  3207. This section describes the @code{scanf} input conversions for reading
  3208. string and character values: @samp{%s}, @samp{%S}, @samp{%[}, @samp{%c},
  3209. and @samp{%C}.
  3210. You have two options for how to receive the input from these
  3211. conversions:
  3212. @itemize @bullet
  3213. @item
  3214. Provide a buffer to store it in. This is the default. You should
  3215. provide an argument of type @code{char *} or @code{wchar_t *} (the
  3216. latter if the @samp{l} modifier is present).
  3217. @strong{Warning:} To make a robust program, you must make sure that the
  3218. input (plus its terminating null) cannot possibly exceed the size of the
  3219. buffer you provide. In general, the only way to do this is to specify a
  3220. maximum field width one less than the buffer size. @strong{If you
  3221. provide the buffer, always specify a maximum field width to prevent
  3222. overflow.}
  3223. @item
  3224. Ask @code{scanf} to allocate a big enough buffer, by specifying the
  3225. @samp{a} flag character. This is a GNU extension. You should provide
  3226. an argument of type @code{char **} for the buffer address to be stored
  3227. in. @xref{Dynamic String Input}.
  3228. @end itemize
  3229. The @samp{%c} conversion is the simplest: it matches a fixed number of
  3230. characters, always. The maximum field width says how many characters to
  3231. read; if you don't specify the maximum, the default is 1. This
  3232. conversion doesn't append a null character to the end of the text it
  3233. reads. It also does not skip over initial whitespace characters. It
  3234. reads precisely the next @var{n} characters, and fails if it cannot get
  3235. that many. Since there is always a maximum field width with @samp{%c}
  3236. (whether specified, or 1 by default), you can always prevent overflow by
  3237. making the buffer long enough.
  3238. @comment Is character == byte here??? --drepper
  3239. If the format is @samp{%lc} or @samp{%C} the function stores wide
  3240. characters which are converted using the conversion determined at the
  3241. time the stream was opened from the external byte stream. The number of
  3242. bytes read from the medium is limited by @code{MB_CUR_LEN * @var{n}} but
  3243. at most @var{n} wide characters get stored in the output string.
  3244. The @samp{%s} conversion matches a string of non-whitespace characters.
  3245. It skips and discards initial whitespace, but stops when it encounters
  3246. more whitespace after having read something. It stores a null character
  3247. at the end of the text that it reads.
  3248. For example, reading the input:
  3249. @smallexample
  3250. hello, world
  3251. @end smallexample
  3252. @noindent
  3253. with the conversion @samp{%10c} produces @code{" hello, wo"}, but
  3254. reading the same input with the conversion @samp{%10s} produces
  3255. @code{"hello,"}.
  3256. @strong{Warning:} If you do not specify a field width for @samp{%s},
  3257. then the number of characters read is limited only by where the next
  3258. whitespace character appears. This almost certainly means that invalid
  3259. input can make your program crash---which is a bug.
  3260. The @samp{%ls} and @samp{%S} format are handled just like @samp{%s}
  3261. except that the external byte sequence is converted using the conversion
  3262. associated with the stream to wide characters with their own encoding.
  3263. A width or precision specified with the format do not directly determine
  3264. how many bytes are read from the stream since they measure wide
  3265. characters. But an upper limit can be computed by multiplying the value
  3266. of the width or precision by @code{MB_CUR_MAX}.
  3267. To read in characters that belong to an arbitrary set of your choice,
  3268. use the @samp{%[} conversion. You specify the set between the @samp{[}
  3269. character and a following @samp{]} character, using the same syntax used
  3270. in regular expressions for explicit sets of characters. As special cases:
  3271. @itemize @bullet
  3272. @item
  3273. A literal @samp{]} character can be specified as the first character
  3274. of the set.
  3275. @item
  3276. An embedded @samp{-} character (that is, one that is not the first or
  3277. last character of the set) is used to specify a range of characters.
  3278. @item
  3279. If a caret character @samp{^} immediately follows the initial @samp{[},
  3280. then the set of allowed input characters is everything @emph{except}
  3281. the characters listed.
  3282. @end itemize
  3283. The @samp{%[} conversion does not skip over initial whitespace
  3284. characters.
  3285. Note that the @dfn{character class} syntax available in character sets
  3286. that appear inside regular expressions (such as @samp{[:alpha:]}) is
  3287. @emph{not} available in the @samp{%[} conversion.
  3288. Here are some examples of @samp{%[} conversions and what they mean:
  3289. @table @samp
  3290. @item %25[1234567890]
  3291. Matches a string of up to 25 digits.
  3292. @item %25[][]
  3293. Matches a string of up to 25 square brackets.
  3294. @item %25[^ \f\n\r\t\v]
  3295. Matches a string up to 25 characters long that doesn't contain any of
  3296. the standard whitespace characters. This is slightly different from
  3297. @samp{%s}, because if the input begins with a whitespace character,
  3298. @samp{%[} reports a matching failure while @samp{%s} simply discards the
  3299. initial whitespace.
  3300. @item %25[a-z]
  3301. Matches up to 25 lowercase characters.
  3302. @end table
  3303. As for @samp{%c} and @samp{%s} the @samp{%[} format is also modified to
  3304. produce wide characters if the @samp{l} modifier is present. All what
  3305. is said about @samp{%ls} above is true for @samp{%l[}.
  3306. One more reminder: the @samp{%s} and @samp{%[} conversions are
  3307. @strong{dangerous} if you don't specify a maximum width or use the
  3308. @samp{a} flag, because input too long would overflow whatever buffer you
  3309. have provided for it. No matter how long your buffer is, a user could
  3310. supply input that is longer. A well-written program reports invalid
  3311. input with a comprehensible error message, not with a crash.
  3312. @node Dynamic String Input
  3313. @subsection Dynamically Allocating String Conversions
  3314. A GNU extension to formatted input lets you safely read a string with no
  3315. maximum size. Using this feature, you don't supply a buffer; instead,
  3316. @code{scanf} allocates a buffer big enough to hold the data and gives
  3317. you its address. To use this feature, write @samp{a} as a flag
  3318. character, as in @samp{%as} or @samp{%a[0-9a-z]}.
  3319. The pointer argument you supply for where to store the input should have
  3320. type @code{char **}. The @code{scanf} function allocates a buffer and
  3321. stores its address in the word that the argument points to. You should
  3322. free the buffer with @code{free} when you no longer need it.
  3323. Here is an example of using the @samp{a} flag with the @samp{%[@dots{}]}
  3324. conversion specification to read a ``variable assignment'' of the form
  3325. @samp{@var{variable} = @var{value}}.
  3326. @smallexample
  3327. @{
  3328. char *variable, *value;
  3329. if (2 > scanf ("%a[a-zA-Z0-9] = %a[^\n]\n",
  3330. &variable, &value))
  3331. @{
  3332. invalid_input_error ();
  3333. return 0;
  3334. @}
  3335. @dots{}
  3336. @}
  3337. @end smallexample
  3338. @node Other Input Conversions
  3339. @subsection Other Input Conversions
  3340. This section describes the miscellaneous input conversions.
  3341. The @samp{%p} conversion is used to read a pointer value. It recognizes
  3342. the same syntax used by the @samp{%p} output conversion for
  3343. @code{printf} (@pxref{Other Output Conversions}); that is, a hexadecimal
  3344. number just as the @samp{%x} conversion accepts. The corresponding
  3345. argument should be of type @code{void **}; that is, the address of a
  3346. place to store a pointer.
  3347. The resulting pointer value is not guaranteed to be valid if it was not
  3348. originally written during the same program execution that reads it in.
  3349. The @samp{%n} conversion produces the number of characters read so far
  3350. by this call. The corresponding argument should be of type @code{int *},
  3351. unless a type modifier is in effect (@pxref{Numeric Input Conversions}).
  3352. This conversion works in the same way as the @samp{%n} conversion for
  3353. @code{printf}; see @ref{Other Output Conversions}, for an example.
  3354. The @samp{%n} conversion is the only mechanism for determining the
  3355. success of literal matches or conversions with suppressed assignments.
  3356. If the @samp{%n} follows the locus of a matching failure, then no value
  3357. is stored for it since @code{scanf} returns before processing the
  3358. @samp{%n}. If you store @code{-1} in that argument slot before calling
  3359. @code{scanf}, the presence of @code{-1} after @code{scanf} indicates an
  3360. error occurred before the @samp{%n} was reached.
  3361. Finally, the @samp{%%} conversion matches a literal @samp{%} character
  3362. in the input stream, without using an argument. This conversion does
  3363. not permit any flags, field width, or type modifier to be specified.
  3364. @node Formatted Input Functions
  3365. @subsection Formatted Input Functions
  3366. Here are the descriptions of the functions for performing formatted
  3367. input.
  3368. Prototypes for these functions are in the header file @file{stdio.h}.
  3369. @pindex stdio.h
  3370. @deftypefun int scanf (const char *@var{template}, @dots{})
  3371. @standards{ISO, stdio.h}
  3372. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3373. The @code{scanf} function reads formatted input from the stream
  3374. @code{stdin} under the control of the template string @var{template}.
  3375. The optional arguments are pointers to the places which receive the
  3376. resulting values.
  3377. The return value is normally the number of successful assignments. If
  3378. an end-of-file condition is detected before any matches are performed,
  3379. including matches against whitespace and literal characters in the
  3380. template, then @code{EOF} is returned.
  3381. @end deftypefun
  3382. @deftypefun int wscanf (const wchar_t *@var{template}, @dots{})
  3383. @standards{ISO, wchar.h}
  3384. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3385. The @code{wscanf} function reads formatted input from the stream
  3386. @code{stdin} under the control of the template string @var{template}.
  3387. The optional arguments are pointers to the places which receive the
  3388. resulting values.
  3389. The return value is normally the number of successful assignments. If
  3390. an end-of-file condition is detected before any matches are performed,
  3391. including matches against whitespace and literal characters in the
  3392. template, then @code{WEOF} is returned.
  3393. @end deftypefun
  3394. @deftypefun int fscanf (FILE *@var{stream}, const char *@var{template}, @dots{})
  3395. @standards{ISO, stdio.h}
  3396. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3397. This function is just like @code{scanf}, except that the input is read
  3398. from the stream @var{stream} instead of @code{stdin}.
  3399. @end deftypefun
  3400. @deftypefun int fwscanf (FILE *@var{stream}, const wchar_t *@var{template}, @dots{})
  3401. @standards{ISO, wchar.h}
  3402. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3403. This function is just like @code{wscanf}, except that the input is read
  3404. from the stream @var{stream} instead of @code{stdin}.
  3405. @end deftypefun
  3406. @deftypefun int sscanf (const char *@var{s}, const char *@var{template}, @dots{})
  3407. @standards{ISO, stdio.h}
  3408. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  3409. This is like @code{scanf}, except that the characters are taken from the
  3410. null-terminated string @var{s} instead of from a stream. Reaching the
  3411. end of the string is treated as an end-of-file condition.
  3412. The behavior of this function is undefined if copying takes place
  3413. between objects that overlap---for example, if @var{s} is also given
  3414. as an argument to receive a string read under control of the @samp{%s},
  3415. @samp{%S}, or @samp{%[} conversion.
  3416. @end deftypefun
  3417. @deftypefun int swscanf (const wchar_t *@var{ws}, const wchar_t *@var{template}, @dots{})
  3418. @standards{ISO, wchar.h}
  3419. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  3420. This is like @code{wscanf}, except that the characters are taken from the
  3421. null-terminated string @var{ws} instead of from a stream. Reaching the
  3422. end of the string is treated as an end-of-file condition.
  3423. The behavior of this function is undefined if copying takes place
  3424. between objects that overlap---for example, if @var{ws} is also given as
  3425. an argument to receive a string read under control of the @samp{%s},
  3426. @samp{%S}, or @samp{%[} conversion.
  3427. @end deftypefun
  3428. @node Variable Arguments Input
  3429. @subsection Variable Arguments Input Functions
  3430. The functions @code{vscanf} and friends are provided so that you can
  3431. define your own variadic @code{scanf}-like functions that make use of
  3432. the same internals as the built-in formatted output functions.
  3433. These functions are analogous to the @code{vprintf} series of output
  3434. functions. @xref{Variable Arguments Output}, for important
  3435. information on how to use them.
  3436. @strong{Portability Note:} The functions listed in this section were
  3437. introduced in @w{ISO C99} and were before available as GNU extensions.
  3438. @deftypefun int vscanf (const char *@var{template}, va_list @var{ap})
  3439. @standards{ISO, stdio.h}
  3440. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3441. This function is similar to @code{scanf}, but instead of taking
  3442. a variable number of arguments directly, it takes an argument list
  3443. pointer @var{ap} of type @code{va_list} (@pxref{Variadic Functions}).
  3444. @end deftypefun
  3445. @deftypefun int vwscanf (const wchar_t *@var{template}, va_list @var{ap})
  3446. @standards{ISO, wchar.h}
  3447. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3448. This function is similar to @code{wscanf}, but instead of taking
  3449. a variable number of arguments directly, it takes an argument list
  3450. pointer @var{ap} of type @code{va_list} (@pxref{Variadic Functions}).
  3451. @end deftypefun
  3452. @deftypefun int vfscanf (FILE *@var{stream}, const char *@var{template}, va_list @var{ap})
  3453. @standards{ISO, stdio.h}
  3454. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3455. This is the equivalent of @code{fscanf} with the variable argument list
  3456. specified directly as for @code{vscanf}.
  3457. @end deftypefun
  3458. @deftypefun int vfwscanf (FILE *@var{stream}, const wchar_t *@var{template}, va_list @var{ap})
  3459. @standards{ISO, wchar.h}
  3460. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  3461. This is the equivalent of @code{fwscanf} with the variable argument list
  3462. specified directly as for @code{vwscanf}.
  3463. @end deftypefun
  3464. @deftypefun int vsscanf (const char *@var{s}, const char *@var{template}, va_list @var{ap})
  3465. @standards{ISO, stdio.h}
  3466. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  3467. This is the equivalent of @code{sscanf} with the variable argument list
  3468. specified directly as for @code{vscanf}.
  3469. @end deftypefun
  3470. @deftypefun int vswscanf (const wchar_t *@var{s}, const wchar_t *@var{template}, va_list @var{ap})
  3471. @standards{ISO, wchar.h}
  3472. @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  3473. This is the equivalent of @code{swscanf} with the variable argument list
  3474. specified directly as for @code{vwscanf}.
  3475. @end deftypefun
  3476. In GNU C, there is a special construct you can use to let the compiler
  3477. know that a function uses a @code{scanf}-style format string. Then it
  3478. can check the number and types of arguments in each call to the
  3479. function, and warn you when they do not match the format string.
  3480. For details, see @ref{Function Attributes, , Declaring Attributes of Functions,
  3481. gcc, Using GNU CC}.
  3482. @node EOF and Errors
  3483. @section End-Of-File and Errors
  3484. @cindex end of file, on a stream
  3485. Many of the functions described in this chapter return the value of the
  3486. macro @code{EOF} to indicate unsuccessful completion of the operation.
  3487. Since @code{EOF} is used to report both end of file and random errors,
  3488. it's often better to use the @code{feof} function to check explicitly
  3489. for end of file and @code{ferror} to check for errors. These functions
  3490. check indicators that are part of the internal state of the stream
  3491. object, indicators set if the appropriate condition was detected by a
  3492. previous I/O operation on that stream.
  3493. The end of file and error conditions are mutually exclusive. For a
  3494. narrow oriented stream, end of file is not considered an error. For
  3495. wide oriented streams, reaching the end of the underlying file can
  3496. result an error if the underlying file ends with an incomplete multibyte
  3497. sequence. This is reported as an error by @code{ferror}, and not as an
  3498. end of file by @code{feof}. End of file on wide oriented streams that
  3499. does not fall into the middle of a multibyte sequence is reported via
  3500. @code{feof}.
  3501. @deftypevr Macro int EOF
  3502. @standards{ISO, stdio.h}
  3503. This macro is an integer value that is returned by a number of narrow
  3504. stream functions to indicate an end-of-file condition, or some other
  3505. error situation. With @theglibc{}, @code{EOF} is @code{-1}. In
  3506. other libraries, its value may be some other negative number.
  3507. This symbol is declared in @file{stdio.h}.
  3508. @end deftypevr
  3509. @deftypevr Macro int WEOF
  3510. @standards{ISO, wchar.h}
  3511. This macro is an integer value that is returned by a number of wide
  3512. stream functions to indicate an end-of-file condition, or some other
  3513. error situation. With @theglibc{}, @code{WEOF} is @code{-1}. In
  3514. other libraries, its value may be some other negative number.
  3515. This symbol is declared in @file{wchar.h}.
  3516. @end deftypevr
  3517. @deftypefun int feof (FILE *@var{stream})
  3518. @standards{ISO, stdio.h}
  3519. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
  3520. The @code{feof} function returns nonzero if and only if the end-of-file
  3521. indicator for the stream @var{stream} is set.
  3522. This symbol is declared in @file{stdio.h}.
  3523. @end deftypefun
  3524. @deftypefun int feof_unlocked (FILE *@var{stream})
  3525. @standards{GNU, stdio.h}
  3526. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  3527. @c There isn't much of a thread unsafety risk in reading a flag word and
  3528. @c testing a bit in it.
  3529. The @code{feof_unlocked} function is equivalent to the @code{feof}
  3530. function except that it does not implicitly lock the stream.
  3531. This function is a GNU extension.
  3532. This symbol is declared in @file{stdio.h}.
  3533. @end deftypefun
  3534. @deftypefun int ferror (FILE *@var{stream})
  3535. @standards{ISO, stdio.h}
  3536. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
  3537. The @code{ferror} function returns nonzero if and only if the error
  3538. indicator for the stream @var{stream} is set, indicating that an error
  3539. has occurred on a previous operation on the stream.
  3540. This symbol is declared in @file{stdio.h}.
  3541. @end deftypefun
  3542. @deftypefun int ferror_unlocked (FILE *@var{stream})
  3543. @standards{GNU, stdio.h}
  3544. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  3545. The @code{ferror_unlocked} function is equivalent to the @code{ferror}
  3546. function except that it does not implicitly lock the stream.
  3547. This function is a GNU extension.
  3548. This symbol is declared in @file{stdio.h}.
  3549. @end deftypefun
  3550. In addition to setting the error indicator associated with the stream,
  3551. the functions that operate on streams also set @code{errno} in the same
  3552. way as the corresponding low-level functions that operate on file
  3553. descriptors. For example, all of the functions that perform output to a
  3554. stream---such as @code{fputc}, @code{printf}, and @code{fflush}---are
  3555. implemented in terms of @code{write}, and all of the @code{errno} error
  3556. conditions defined for @code{write} are meaningful for these functions.
  3557. For more information about the descriptor-level I/O functions, see
  3558. @ref{Low-Level I/O}.
  3559. @node Error Recovery
  3560. @section Recovering from errors
  3561. You may explicitly clear the error and EOF flags with the @code{clearerr}
  3562. function.
  3563. @deftypefun void clearerr (FILE *@var{stream})
  3564. @standards{ISO, stdio.h}
  3565. @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
  3566. This function clears the end-of-file and error indicators for the
  3567. stream @var{stream}.
  3568. The file positioning functions (@pxref{File Positioning}) also clear the
  3569. end-of-file indicator for the stream.
  3570. @end deftypefun
  3571. @deftypefun void clearerr_unlocked (FILE *@var{stream})
  3572. @standards{GNU, stdio.h}
  3573. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@assafe{}@acsafe{}}
  3574. The @code{clearerr_unlocked} function is equivalent to the @code{clearerr}
  3575. function except that it does not implicitly lock the stream.
  3576. This function is a GNU extension.
  3577. @end deftypefun
  3578. Note that it is @emph{not} correct to just clear the error flag and retry
  3579. a failed stream operation. After a failed write, any number of
  3580. characters since the last buffer flush may have been committed to the
  3581. file, while some buffered data may have been discarded. Merely retrying
  3582. can thus cause lost or repeated data.
  3583. A failed read may leave the file pointer in an inappropriate position for
  3584. a second try. In both cases, you should seek to a known position before
  3585. retrying.
  3586. Most errors that can happen are not recoverable --- a second try will
  3587. always fail again in the same way. So usually it is best to give up and
  3588. report the error to the user, rather than install complicated recovery
  3589. logic.
  3590. One important exception is @code{EINTR} (@pxref{Interrupted Primitives}).
  3591. Many stream I/O implementations will treat it as an ordinary error, which
  3592. can be quite inconvenient. You can avoid this hassle by installing all
  3593. signals with the @code{SA_RESTART} flag.
  3594. For similar reasons, setting nonblocking I/O on a stream's file
  3595. descriptor is not usually advisable.
  3596. @node Binary Streams
  3597. @section Text and Binary Streams
  3598. @gnusystems{} and other POSIX-compatible operating systems organize all
  3599. files as uniform sequences of characters. However, some other systems
  3600. make a distinction between files containing text and files containing
  3601. binary data, and the input and output facilities of @w{ISO C} provide for
  3602. this distinction. This section tells you how to write programs portable
  3603. to such systems.
  3604. @cindex text stream
  3605. @cindex binary stream
  3606. When you open a stream, you can specify either a @dfn{text stream} or a
  3607. @dfn{binary stream}. You indicate that you want a binary stream by
  3608. specifying the @samp{b} modifier in the @var{opentype} argument to
  3609. @code{fopen}; see @ref{Opening Streams}. Without this
  3610. option, @code{fopen} opens the file as a text stream.
  3611. Text and binary streams differ in several ways:
  3612. @itemize @bullet
  3613. @item
  3614. The data read from a text stream is divided into @dfn{lines} which are
  3615. terminated by newline (@code{'\n'}) characters, while a binary stream is
  3616. simply a long series of characters. A text stream might on some systems
  3617. fail to handle lines more than 254 characters long (including the
  3618. terminating newline character).
  3619. @cindex lines (in a text file)
  3620. @item
  3621. If the system does not use POSIX-style in-band signalling to indicate
  3622. line termination, it can be impossibe to write anything to a text stream
  3623. without adding a line terminator. As a result, flushing a text stream
  3624. (by calling @code{fflush}, for example) may produce a logical line
  3625. terminator even if no @code{'\n'} character was written by the program.
  3626. @item
  3627. Text files may contain lines that embed @code{'\n'} characters that are
  3628. not treated as line terminators by the system. C programs cannot read
  3629. such text files reliably using the @file{stdio.h} facilities.
  3630. @item
  3631. On some systems, text files can contain only printing characters,
  3632. horizontal tab characters, and newlines, and so text streams may not
  3633. support other characters. However, binary streams can handle any
  3634. character value.
  3635. @item
  3636. Space characters that are written immediately preceding a newline
  3637. character in a text stream may disappear when the file is read in again.
  3638. @item
  3639. More generally, there need not be a one-to-one mapping between
  3640. characters that are read from or written to a text stream, and the
  3641. characters in the actual file.
  3642. @end itemize
  3643. Since a binary stream is always more capable and more predictable than a
  3644. text stream, you might wonder what purpose text streams serve. Why not
  3645. simply always use binary streams? The answer is that on these operating
  3646. systems, text and binary streams use different file formats, and the
  3647. only way to read or write ``an ordinary file of text'' that can work
  3648. with other text-oriented programs is through a text stream.
  3649. In @theglibc{}, and on all POSIX systems, there is no difference
  3650. between text streams and binary streams. When you open a stream, you
  3651. get the same kind of stream regardless of whether you ask for binary.
  3652. This stream can handle any file content, and has none of the
  3653. restrictions that text streams sometimes have.
  3654. @node File Positioning
  3655. @section File Positioning
  3656. @cindex file positioning on a stream
  3657. @cindex positioning a stream
  3658. @cindex seeking on a stream
  3659. The @dfn{file position} of a stream describes where in the file the
  3660. stream is currently reading or writing. I/O on the stream advances the
  3661. file position through the file. On @gnusystems{}, the file position is
  3662. represented as an integer, which counts the number of bytes from the
  3663. beginning of the file. @xref{File Position}.
  3664. During I/O to an ordinary disk file, you can change the file position
  3665. whenever you wish, so as to read or write any portion of the file. Some
  3666. other kinds of files may also permit this. Files which support changing
  3667. the file position are sometimes referred to as @dfn{random-access}
  3668. files.
  3669. You can use the functions in this section to examine or modify the file
  3670. position indicator associated with a stream. The symbols listed below
  3671. are declared in the header file @file{stdio.h}.
  3672. @pindex stdio.h
  3673. @deftypefun {long int} ftell (FILE *@var{stream})
  3674. @standards{ISO, stdio.h}
  3675. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3676. This function returns the current file position of the stream
  3677. @var{stream}.
  3678. This function can fail if the stream doesn't support file positioning,
  3679. or if the file position can't be represented in a @code{long int}, and
  3680. possibly for other reasons as well. If a failure occurs, a value of
  3681. @code{-1} is returned.
  3682. @end deftypefun
  3683. @deftypefun off_t ftello (FILE *@var{stream})
  3684. @standards{Unix98, stdio.h}
  3685. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3686. The @code{ftello} function is similar to @code{ftell}, except that it
  3687. returns a value of type @code{off_t}. Systems which support this type
  3688. use it to describe all file positions, unlike the POSIX specification
  3689. which uses a long int. The two are not necessarily the same size.
  3690. Therefore, using ftell can lead to problems if the implementation is
  3691. written on top of a POSIX compliant low-level I/O implementation, and using
  3692. @code{ftello} is preferable whenever it is available.
  3693. If this function fails it returns @code{(off_t) -1}. This can happen due
  3694. to missing support for file positioning or internal errors. Otherwise
  3695. the return value is the current file position.
  3696. The function is an extension defined in the Unix Single Specification
  3697. version 2.
  3698. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  3699. 32 bit system this function is in fact @code{ftello64}. I.e., the
  3700. LFS interface transparently replaces the old interface.
  3701. @end deftypefun
  3702. @deftypefun off64_t ftello64 (FILE *@var{stream})
  3703. @standards{Unix98, stdio.h}
  3704. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3705. This function is similar to @code{ftello} with the only difference that
  3706. the return value is of type @code{off64_t}. This also requires that the
  3707. stream @var{stream} was opened using either @code{fopen64},
  3708. @code{freopen64}, or @code{tmpfile64} since otherwise the underlying
  3709. file operations to position the file pointer beyond the @twoexp{31}
  3710. bytes limit might fail.
  3711. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
  3712. bits machine this function is available under the name @code{ftello}
  3713. and so transparently replaces the old interface.
  3714. @end deftypefun
  3715. @deftypefun int fseek (FILE *@var{stream}, long int @var{offset}, int @var{whence})
  3716. @standards{ISO, stdio.h}
  3717. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3718. The @code{fseek} function is used to change the file position of the
  3719. stream @var{stream}. The value of @var{whence} must be one of the
  3720. constants @code{SEEK_SET}, @code{SEEK_CUR}, or @code{SEEK_END}, to
  3721. indicate whether the @var{offset} is relative to the beginning of the
  3722. file, the current file position, or the end of the file, respectively.
  3723. This function returns a value of zero if the operation was successful,
  3724. and a nonzero value to indicate failure. A successful call also clears
  3725. the end-of-file indicator of @var{stream} and discards any characters
  3726. that were ``pushed back'' by the use of @code{ungetc}.
  3727. @code{fseek} either flushes any buffered output before setting the file
  3728. position or else remembers it so it will be written later in its proper
  3729. place in the file.
  3730. @end deftypefun
  3731. @deftypefun int fseeko (FILE *@var{stream}, off_t @var{offset}, int @var{whence})
  3732. @standards{Unix98, stdio.h}
  3733. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3734. This function is similar to @code{fseek} but it corrects a problem with
  3735. @code{fseek} in a system with POSIX types. Using a value of type
  3736. @code{long int} for the offset is not compatible with POSIX.
  3737. @code{fseeko} uses the correct type @code{off_t} for the @var{offset}
  3738. parameter.
  3739. For this reason it is a good idea to prefer @code{ftello} whenever it is
  3740. available since its functionality is (if different at all) closer the
  3741. underlying definition.
  3742. The functionality and return value are the same as for @code{fseek}.
  3743. The function is an extension defined in the Unix Single Specification
  3744. version 2.
  3745. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  3746. 32 bit system this function is in fact @code{fseeko64}. I.e., the
  3747. LFS interface transparently replaces the old interface.
  3748. @end deftypefun
  3749. @deftypefun int fseeko64 (FILE *@var{stream}, off64_t @var{offset}, int @var{whence})
  3750. @standards{Unix98, stdio.h}
  3751. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3752. This function is similar to @code{fseeko} with the only difference that
  3753. the @var{offset} parameter is of type @code{off64_t}. This also
  3754. requires that the stream @var{stream} was opened using either
  3755. @code{fopen64}, @code{freopen64}, or @code{tmpfile64} since otherwise
  3756. the underlying file operations to position the file pointer beyond the
  3757. @twoexp{31} bytes limit might fail.
  3758. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
  3759. bits machine this function is available under the name @code{fseeko}
  3760. and so transparently replaces the old interface.
  3761. @end deftypefun
  3762. @strong{Portability Note:} In non-POSIX systems, @code{ftell},
  3763. @code{ftello}, @code{fseek} and @code{fseeko} might work reliably only
  3764. on binary streams. @xref{Binary Streams}.
  3765. The following symbolic constants are defined for use as the @var{whence}
  3766. argument to @code{fseek}. They are also used with the @code{lseek}
  3767. function (@pxref{I/O Primitives}) and to specify offsets for file locks
  3768. (@pxref{Control Operations}).
  3769. @deftypevr Macro int SEEK_SET
  3770. @standards{ISO, stdio.h}
  3771. This is an integer constant which, when used as the @var{whence}
  3772. argument to the @code{fseek} or @code{fseeko} functions, specifies that
  3773. the offset provided is relative to the beginning of the file.
  3774. @end deftypevr
  3775. @deftypevr Macro int SEEK_CUR
  3776. @standards{ISO, stdio.h}
  3777. This is an integer constant which, when used as the @var{whence}
  3778. argument to the @code{fseek} or @code{fseeko} functions, specifies that
  3779. the offset provided is relative to the current file position.
  3780. @end deftypevr
  3781. @deftypevr Macro int SEEK_END
  3782. @standards{ISO, stdio.h}
  3783. This is an integer constant which, when used as the @var{whence}
  3784. argument to the @code{fseek} or @code{fseeko} functions, specifies that
  3785. the offset provided is relative to the end of the file.
  3786. @end deftypevr
  3787. @deftypefun void rewind (FILE *@var{stream})
  3788. @standards{ISO, stdio.h}
  3789. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3790. The @code{rewind} function positions the stream @var{stream} at the
  3791. beginning of the file. It is equivalent to calling @code{fseek} or
  3792. @code{fseeko} on the @var{stream} with an @var{offset} argument of
  3793. @code{0L} and a @var{whence} argument of @code{SEEK_SET}, except that
  3794. the return value is discarded and the error indicator for the stream is
  3795. reset.
  3796. @end deftypefun
  3797. These three aliases for the @samp{SEEK_@dots{}} constants exist for the
  3798. sake of compatibility with older BSD systems. They are defined in two
  3799. different header files: @file{fcntl.h} and @file{sys/file.h}.
  3800. @vtable @code
  3801. @item L_SET
  3802. @standards{BSD, sys/file.h}
  3803. An alias for @code{SEEK_SET}.
  3804. @item L_INCR
  3805. @standards{BSD, sys/file.h}
  3806. An alias for @code{SEEK_CUR}.
  3807. @item L_XTND
  3808. @standards{BSD, sys/file.h}
  3809. An alias for @code{SEEK_END}.
  3810. @end vtable
  3811. @node Portable Positioning
  3812. @section Portable File-Position Functions
  3813. On @gnusystems{}, the file position is truly a character count. You
  3814. can specify any character count value as an argument to @code{fseek} or
  3815. @code{fseeko} and get reliable results for any random access file.
  3816. However, some @w{ISO C} systems do not represent file positions in this
  3817. way.
  3818. On some systems where text streams truly differ from binary streams, it
  3819. is impossible to represent the file position of a text stream as a count
  3820. of characters from the beginning of the file. For example, the file
  3821. position on some systems must encode both a record offset within the
  3822. file, and a character offset within the record.
  3823. As a consequence, if you want your programs to be portable to these
  3824. systems, you must observe certain rules:
  3825. @itemize @bullet
  3826. @item
  3827. The value returned from @code{ftell} on a text stream has no predictable
  3828. relationship to the number of characters you have read so far. The only
  3829. thing you can rely on is that you can use it subsequently as the
  3830. @var{offset} argument to @code{fseek} or @code{fseeko} to move back to
  3831. the same file position.
  3832. @item
  3833. In a call to @code{fseek} or @code{fseeko} on a text stream, either the
  3834. @var{offset} must be zero, or @var{whence} must be @code{SEEK_SET} and
  3835. the @var{offset} must be the result of an earlier call to @code{ftell}
  3836. on the same stream.
  3837. @item
  3838. The value of the file position indicator of a text stream is undefined
  3839. while there are characters that have been pushed back with @code{ungetc}
  3840. that haven't been read or discarded. @xref{Unreading}.
  3841. @end itemize
  3842. But even if you observe these rules, you may still have trouble for long
  3843. files, because @code{ftell} and @code{fseek} use a @code{long int} value
  3844. to represent the file position. This type may not have room to encode
  3845. all the file positions in a large file. Using the @code{ftello} and
  3846. @code{fseeko} functions might help here since the @code{off_t} type is
  3847. expected to be able to hold all file position values but this still does
  3848. not help to handle additional information which must be associated with
  3849. a file position.
  3850. So if you do want to support systems with peculiar encodings for the
  3851. file positions, it is better to use the functions @code{fgetpos} and
  3852. @code{fsetpos} instead. These functions represent the file position
  3853. using the data type @code{fpos_t}, whose internal representation varies
  3854. from system to system.
  3855. These symbols are declared in the header file @file{stdio.h}.
  3856. @pindex stdio.h
  3857. @deftp {Data Type} fpos_t
  3858. @standards{ISO, stdio.h}
  3859. This is the type of an object that can encode information about the
  3860. file position of a stream, for use by the functions @code{fgetpos} and
  3861. @code{fsetpos}.
  3862. In @theglibc{}, @code{fpos_t} is an opaque data structure that
  3863. contains internal data to represent file offset and conversion state
  3864. information. In other systems, it might have a different internal
  3865. representation.
  3866. When compiling with @code{_FILE_OFFSET_BITS == 64} on a 32 bit machine
  3867. this type is in fact equivalent to @code{fpos64_t} since the LFS
  3868. interface transparently replaces the old interface.
  3869. @end deftp
  3870. @deftp {Data Type} fpos64_t
  3871. @standards{Unix98, stdio.h}
  3872. This is the type of an object that can encode information about the
  3873. file position of a stream, for use by the functions @code{fgetpos64} and
  3874. @code{fsetpos64}.
  3875. In @theglibc{}, @code{fpos64_t} is an opaque data structure that
  3876. contains internal data to represent file offset and conversion state
  3877. information. In other systems, it might have a different internal
  3878. representation.
  3879. @end deftp
  3880. @deftypefun int fgetpos (FILE *@var{stream}, fpos_t *@var{position})
  3881. @standards{ISO, stdio.h}
  3882. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3883. This function stores the value of the file position indicator for the
  3884. stream @var{stream} in the @code{fpos_t} object pointed to by
  3885. @var{position}. If successful, @code{fgetpos} returns zero; otherwise
  3886. it returns a nonzero value and stores an implementation-defined positive
  3887. value in @code{errno}.
  3888. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  3889. 32 bit system the function is in fact @code{fgetpos64}. I.e., the LFS
  3890. interface transparently replaces the old interface.
  3891. @end deftypefun
  3892. @deftypefun int fgetpos64 (FILE *@var{stream}, fpos64_t *@var{position})
  3893. @standards{Unix98, stdio.h}
  3894. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3895. This function is similar to @code{fgetpos} but the file position is
  3896. returned in a variable of type @code{fpos64_t} to which @var{position}
  3897. points.
  3898. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
  3899. bits machine this function is available under the name @code{fgetpos}
  3900. and so transparently replaces the old interface.
  3901. @end deftypefun
  3902. @deftypefun int fsetpos (FILE *@var{stream}, const fpos_t *@var{position})
  3903. @standards{ISO, stdio.h}
  3904. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3905. This function sets the file position indicator for the stream @var{stream}
  3906. to the position @var{position}, which must have been set by a previous
  3907. call to @code{fgetpos} on the same stream. If successful, @code{fsetpos}
  3908. clears the end-of-file indicator on the stream, discards any characters
  3909. that were ``pushed back'' by the use of @code{ungetc}, and returns a value
  3910. of zero. Otherwise, @code{fsetpos} returns a nonzero value and stores
  3911. an implementation-defined positive value in @code{errno}.
  3912. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  3913. 32 bit system the function is in fact @code{fsetpos64}. I.e., the LFS
  3914. interface transparently replaces the old interface.
  3915. @end deftypefun
  3916. @deftypefun int fsetpos64 (FILE *@var{stream}, const fpos64_t *@var{position})
  3917. @standards{Unix98, stdio.h}
  3918. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  3919. This function is similar to @code{fsetpos} but the file position used
  3920. for positioning is provided in a variable of type @code{fpos64_t} to
  3921. which @var{position} points.
  3922. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
  3923. bits machine this function is available under the name @code{fsetpos}
  3924. and so transparently replaces the old interface.
  3925. @end deftypefun
  3926. @node Stream Buffering
  3927. @section Stream Buffering
  3928. @cindex buffering of streams
  3929. Characters that are written to a stream are normally accumulated and
  3930. transmitted asynchronously to the file in a block, instead of appearing
  3931. as soon as they are output by the application program. Similarly,
  3932. streams often retrieve input from the host environment in blocks rather
  3933. than on a character-by-character basis. This is called @dfn{buffering}.
  3934. If you are writing programs that do interactive input and output using
  3935. streams, you need to understand how buffering works when you design the
  3936. user interface to your program. Otherwise, you might find that output
  3937. (such as progress or prompt messages) doesn't appear when you intended
  3938. it to, or displays some other unexpected behavior.
  3939. This section deals only with controlling when characters are transmitted
  3940. between the stream and the file or device, and @emph{not} with how
  3941. things like echoing, flow control, and the like are handled on specific
  3942. classes of devices. For information on common control operations on
  3943. terminal devices, see @ref{Low-Level Terminal Interface}.
  3944. You can bypass the stream buffering facilities altogether by using the
  3945. low-level input and output functions that operate on file descriptors
  3946. instead. @xref{Low-Level I/O}.
  3947. @menu
  3948. * Buffering Concepts:: Terminology is defined here.
  3949. * Flushing Buffers:: How to ensure that output buffers are flushed.
  3950. * Controlling Buffering:: How to specify what kind of buffering to use.
  3951. @end menu
  3952. @node Buffering Concepts
  3953. @subsection Buffering Concepts
  3954. There are three different kinds of buffering strategies:
  3955. @itemize @bullet
  3956. @item
  3957. Characters written to or read from an @dfn{unbuffered} stream are
  3958. transmitted individually to or from the file as soon as possible.
  3959. @cindex unbuffered stream
  3960. @item
  3961. Characters written to a @dfn{line buffered} stream are transmitted to
  3962. the file in blocks when a newline character is encountered.
  3963. @cindex line buffered stream
  3964. @item
  3965. Characters written to or read from a @dfn{fully buffered} stream are
  3966. transmitted to or from the file in blocks of arbitrary size.
  3967. @cindex fully buffered stream
  3968. @end itemize
  3969. Newly opened streams are normally fully buffered, with one exception: a
  3970. stream connected to an interactive device such as a terminal is
  3971. initially line buffered. @xref{Controlling Buffering}, for information
  3972. on how to select a different kind of buffering. Usually the automatic
  3973. selection gives you the most convenient kind of buffering for the file
  3974. or device you open.
  3975. The use of line buffering for interactive devices implies that output
  3976. messages ending in a newline will appear immediately---which is usually
  3977. what you want. Output that doesn't end in a newline might or might not
  3978. show up immediately, so if you want them to appear immediately, you
  3979. should flush buffered output explicitly with @code{fflush}, as described
  3980. in @ref{Flushing Buffers}.
  3981. @node Flushing Buffers
  3982. @subsection Flushing Buffers
  3983. @cindex flushing a stream
  3984. @dfn{Flushing} output on a buffered stream means transmitting all
  3985. accumulated characters to the file. There are many circumstances when
  3986. buffered output on a stream is flushed automatically:
  3987. @itemize @bullet
  3988. @item
  3989. When you try to do output and the output buffer is full.
  3990. @item
  3991. When the stream is closed. @xref{Closing Streams}.
  3992. @item
  3993. When the program terminates by calling @code{exit}.
  3994. @xref{Normal Termination}.
  3995. @item
  3996. When a newline is written, if the stream is line buffered.
  3997. @item
  3998. Whenever an input operation on @emph{any} stream actually reads data
  3999. from its file.
  4000. @end itemize
  4001. If you want to flush the buffered output at another time, call
  4002. @code{fflush}, which is declared in the header file @file{stdio.h}.
  4003. @pindex stdio.h
  4004. @deftypefun int fflush (FILE *@var{stream})
  4005. @standards{ISO, stdio.h}
  4006. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  4007. This function causes any buffered output on @var{stream} to be delivered
  4008. to the file. If @var{stream} is a null pointer, then
  4009. @code{fflush} causes buffered output on @emph{all} open output streams
  4010. to be flushed.
  4011. This function returns @code{EOF} if a write error occurs, or zero
  4012. otherwise.
  4013. @end deftypefun
  4014. @deftypefun int fflush_unlocked (FILE *@var{stream})
  4015. @standards{POSIX, stdio.h}
  4016. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  4017. The @code{fflush_unlocked} function is equivalent to the @code{fflush}
  4018. function except that it does not implicitly lock the stream.
  4019. @end deftypefun
  4020. The @code{fflush} function can be used to flush all streams currently
  4021. opened. While this is useful in some situations it does often more than
  4022. necessary since it might be done in situations when terminal input is
  4023. required and the program wants to be sure that all output is visible on
  4024. the terminal. But this means that only line buffered streams have to be
  4025. flushed. Solaris introduced a function especially for this. It was
  4026. always available in @theglibc{} in some form but never officially
  4027. exported.
  4028. @deftypefun void _flushlbf (void)
  4029. @standards{GNU, stdio_ext.h}
  4030. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  4031. The @code{_flushlbf} function flushes all line buffered streams
  4032. currently opened.
  4033. This function is declared in the @file{stdio_ext.h} header.
  4034. @end deftypefun
  4035. In some situations it might be useful to not flush the output pending
  4036. for a stream but instead simply forget it. If transmission is costly
  4037. and the output is not needed anymore this is valid reasoning. In this
  4038. situation a non-standard function introduced in Solaris and available in
  4039. @theglibc{} can be used.
  4040. @deftypefun void __fpurge (FILE *@var{stream})
  4041. @standards{GNU, stdio_ext.h}
  4042. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
  4043. The @code{__fpurge} function causes the buffer of the stream
  4044. @var{stream} to be emptied. If the stream is currently in read mode all
  4045. input in the buffer is lost. If the stream is in output mode the
  4046. buffered output is not written to the device (or whatever other
  4047. underlying storage) and the buffer is cleared.
  4048. This function is declared in @file{stdio_ext.h}.
  4049. @end deftypefun
  4050. @node Controlling Buffering
  4051. @subsection Controlling Which Kind of Buffering
  4052. After opening a stream (but before any other operations have been
  4053. performed on it), you can explicitly specify what kind of buffering you
  4054. want it to have using the @code{setvbuf} function.
  4055. @cindex buffering, controlling
  4056. The facilities listed in this section are declared in the header
  4057. file @file{stdio.h}.
  4058. @pindex stdio.h
  4059. @deftypefun int setvbuf (FILE *@var{stream}, char *@var{buf}, int @var{mode}, size_t @var{size})
  4060. @standards{ISO, stdio.h}
  4061. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  4062. This function is used to specify that the stream @var{stream} should
  4063. have the buffering mode @var{mode}, which can be either @code{_IOFBF}
  4064. (for full buffering), @code{_IOLBF} (for line buffering), or
  4065. @code{_IONBF} (for unbuffered input/output).
  4066. If you specify a null pointer as the @var{buf} argument, then @code{setvbuf}
  4067. allocates a buffer itself using @code{malloc}. This buffer will be freed
  4068. when you close the stream.
  4069. Otherwise, @var{buf} should be a character array that can hold at least
  4070. @var{size} characters. You should not free the space for this array as
  4071. long as the stream remains open and this array remains its buffer. You
  4072. should usually either allocate it statically, or @code{malloc}
  4073. (@pxref{Unconstrained Allocation}) the buffer. Using an automatic array
  4074. is not a good idea unless you close the file before exiting the block
  4075. that declares the array.
  4076. While the array remains a stream buffer, the stream I/O functions will
  4077. use the buffer for their internal purposes. You shouldn't try to access
  4078. the values in the array directly while the stream is using it for
  4079. buffering.
  4080. The @code{setvbuf} function returns zero on success, or a nonzero value
  4081. if the value of @var{mode} is not valid or if the request could not
  4082. be honored.
  4083. @end deftypefun
  4084. @deftypevr Macro int _IOFBF
  4085. @standards{ISO, stdio.h}
  4086. The value of this macro is an integer constant expression that can be
  4087. used as the @var{mode} argument to the @code{setvbuf} function to
  4088. specify that the stream should be fully buffered.
  4089. @end deftypevr
  4090. @deftypevr Macro int _IOLBF
  4091. @standards{ISO, stdio.h}
  4092. The value of this macro is an integer constant expression that can be
  4093. used as the @var{mode} argument to the @code{setvbuf} function to
  4094. specify that the stream should be line buffered.
  4095. @end deftypevr
  4096. @deftypevr Macro int _IONBF
  4097. @standards{ISO, stdio.h}
  4098. The value of this macro is an integer constant expression that can be
  4099. used as the @var{mode} argument to the @code{setvbuf} function to
  4100. specify that the stream should be unbuffered.
  4101. @end deftypevr
  4102. @deftypevr Macro int BUFSIZ
  4103. @standards{ISO, stdio.h}
  4104. The value of this macro is an integer constant expression that is good
  4105. to use for the @var{size} argument to @code{setvbuf}. This value is
  4106. guaranteed to be at least @code{256}.
  4107. The value of @code{BUFSIZ} is chosen on each system so as to make stream
  4108. I/O efficient. So it is a good idea to use @code{BUFSIZ} as the size
  4109. for the buffer when you call @code{setvbuf}.
  4110. Actually, you can get an even better value to use for the buffer size
  4111. by means of the @code{fstat} system call: it is found in the
  4112. @code{st_blksize} field of the file attributes. @xref{Attribute Meanings}.
  4113. Sometimes people also use @code{BUFSIZ} as the allocation size of
  4114. buffers used for related purposes, such as strings used to receive a
  4115. line of input with @code{fgets} (@pxref{Character Input}). There is no
  4116. particular reason to use @code{BUFSIZ} for this instead of any other
  4117. integer, except that it might lead to doing I/O in chunks of an
  4118. efficient size.
  4119. @end deftypevr
  4120. @deftypefun void setbuf (FILE *@var{stream}, char *@var{buf})
  4121. @standards{ISO, stdio.h}
  4122. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  4123. If @var{buf} is a null pointer, the effect of this function is
  4124. equivalent to calling @code{setvbuf} with a @var{mode} argument of
  4125. @code{_IONBF}. Otherwise, it is equivalent to calling @code{setvbuf}
  4126. with @var{buf}, and a @var{mode} of @code{_IOFBF} and a @var{size}
  4127. argument of @code{BUFSIZ}.
  4128. The @code{setbuf} function is provided for compatibility with old code;
  4129. use @code{setvbuf} in all new programs.
  4130. @end deftypefun
  4131. @deftypefun void setbuffer (FILE *@var{stream}, char *@var{buf}, size_t @var{size})
  4132. @standards{BSD, stdio.h}
  4133. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  4134. If @var{buf} is a null pointer, this function makes @var{stream} unbuffered.
  4135. Otherwise, it makes @var{stream} fully buffered using @var{buf} as the
  4136. buffer. The @var{size} argument specifies the length of @var{buf}.
  4137. This function is provided for compatibility with old BSD code. Use
  4138. @code{setvbuf} instead.
  4139. @end deftypefun
  4140. @deftypefun void setlinebuf (FILE *@var{stream})
  4141. @standards{BSD, stdio.h}
  4142. @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
  4143. This function makes @var{stream} be line buffered, and allocates the
  4144. buffer for you.
  4145. This function is provided for compatibility with old BSD code. Use
  4146. @code{setvbuf} instead.
  4147. @end deftypefun
  4148. It is possible to query whether a given stream is line buffered or not
  4149. using a non-standard function introduced in Solaris and available in
  4150. @theglibc{}.
  4151. @deftypefun int __flbf (FILE *@var{stream})
  4152. @standards{GNU, stdio_ext.h}
  4153. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  4154. The @code{__flbf} function will return a nonzero value in case the
  4155. stream @var{stream} is line buffered. Otherwise the return value is
  4156. zero.
  4157. This function is declared in the @file{stdio_ext.h} header.
  4158. @end deftypefun
  4159. Two more extensions allow to determine the size of the buffer and how
  4160. much of it is used. These functions were also introduced in Solaris.
  4161. @deftypefun size_t __fbufsize (FILE *@var{stream})
  4162. @standards{GNU, stdio_ext.h}
  4163. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acsafe{}}
  4164. The @code{__fbufsize} function return the size of the buffer in the
  4165. stream @var{stream}. This value can be used to optimize the use of the
  4166. stream.
  4167. This function is declared in the @file{stdio_ext.h} header.
  4168. @end deftypefun
  4169. @deftypefun size_t __fpending (FILE *@var{stream})
  4170. @standards{GNU, stdio_ext.h}
  4171. @safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acsafe{}}
  4172. The @code{__fpending}
  4173. function returns the number of bytes currently in the output buffer.
  4174. For wide-oriented streams the measuring unit is wide characters. This
  4175. function should not be used on buffers in read mode or opened read-only.
  4176. This function is declared in the @file{stdio_ext.h} header.
  4177. @end deftypefun
  4178. @node Other Kinds of Streams
  4179. @section Other Kinds of Streams
  4180. @Theglibc{} provides ways for you to define additional kinds of
  4181. streams that do not necessarily correspond to an open file.
  4182. One such type of stream takes input from or writes output to a string.
  4183. These kinds of streams are used internally to implement the
  4184. @code{sprintf} and @code{sscanf} functions. You can also create such a
  4185. stream explicitly, using the functions described in @ref{String Streams}.
  4186. More generally, you can define streams that do input/output to arbitrary
  4187. objects using functions supplied by your program. This protocol is
  4188. discussed in @ref{Custom Streams}.
  4189. @strong{Portability Note:} The facilities described in this section are
  4190. specific to GNU. Other systems or C implementations might or might not
  4191. provide equivalent functionality.
  4192. @menu
  4193. * String Streams:: Streams that get data from or put data in
  4194. a string or memory buffer.
  4195. * Custom Streams:: Defining your own streams with an arbitrary
  4196. input data source and/or output data sink.
  4197. @end menu
  4198. @node String Streams
  4199. @subsection String Streams
  4200. @cindex stream, for I/O to a string
  4201. @cindex string stream
  4202. The @code{fmemopen} and @code{open_memstream} functions allow you to do
  4203. I/O to a string or memory buffer. These facilities are declared in
  4204. @file{stdio.h}.
  4205. @pindex stdio.h
  4206. @deftypefun {FILE *} fmemopen (void *@var{buf}, size_t @var{size}, const char *@var{opentype})
  4207. @standards{GNU, stdio.h}
  4208. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @aculock{}}}
  4209. @c Unlike open_memstream, fmemopen does (indirectly) call _IO_link_in,
  4210. @c bringing with it additional potential for async trouble with
  4211. @c list_all_lock.
  4212. This function opens a stream that allows the access specified by the
  4213. @var{opentype} argument, that reads from or writes to the buffer specified
  4214. by the argument @var{buf}. This array must be at least @var{size} bytes long.
  4215. If you specify a null pointer as the @var{buf} argument, @code{fmemopen}
  4216. dynamically allocates an array @var{size} bytes long (as with @code{malloc};
  4217. @pxref{Unconstrained Allocation}). This is really only useful
  4218. if you are going to write things to the buffer and then read them back
  4219. in again, because you have no way of actually getting a pointer to the
  4220. buffer (for this, try @code{open_memstream}, below). The buffer is
  4221. freed when the stream is closed.
  4222. The argument @var{opentype} is the same as in @code{fopen}
  4223. (@pxref{Opening Streams}). If the @var{opentype} specifies
  4224. append mode, then the initial file position is set to the first null
  4225. character in the buffer. Otherwise the initial file position is at the
  4226. beginning of the buffer.
  4227. When a stream open for writing is flushed or closed, a null character
  4228. (zero byte) is written at the end of the buffer if it fits. You
  4229. should add an extra byte to the @var{size} argument to account for this.
  4230. Attempts to write more than @var{size} bytes to the buffer result
  4231. in an error.
  4232. For a stream open for reading, null characters (zero bytes) in the
  4233. buffer do not count as ``end of file''. Read operations indicate end of
  4234. file only when the file position advances past @var{size} bytes. So, if
  4235. you want to read characters from a null-terminated string, you should
  4236. supply the length of the string as the @var{size} argument.
  4237. @end deftypefun
  4238. Here is an example of using @code{fmemopen} to create a stream for
  4239. reading from a string:
  4240. @smallexample
  4241. @include memopen.c.texi
  4242. @end smallexample
  4243. This program produces the following output:
  4244. @smallexample
  4245. Got f
  4246. Got o
  4247. Got o
  4248. Got b
  4249. Got a
  4250. Got r
  4251. @end smallexample
  4252. @deftypefun {FILE *} open_memstream (char **@var{ptr}, size_t *@var{sizeloc})
  4253. @standards{GNU, stdio.h}
  4254. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
  4255. This function opens a stream for writing to a buffer. The buffer is
  4256. allocated dynamically and grown as necessary, using @code{malloc}.
  4257. After you've closed the stream, this buffer is your responsibility to
  4258. clean up using @code{free} or @code{realloc}. @xref{Unconstrained Allocation}.
  4259. When the stream is closed with @code{fclose} or flushed with
  4260. @code{fflush}, the locations @var{ptr} and @var{sizeloc} are updated to
  4261. contain the pointer to the buffer and its size. The values thus stored
  4262. remain valid only as long as no further output on the stream takes
  4263. place. If you do more output, you must flush the stream again to store
  4264. new values before you use them again.
  4265. A null character is written at the end of the buffer when the stream
  4266. is flushed, and at the current location when closed (these locations
  4267. may be different if @code{fseek} is used). This null character is
  4268. @emph{not} included in the size value stored at @var{sizeloc}.
  4269. You can move the stream's file position with @code{fseek} or
  4270. @code{fseeko} (@pxref{File Positioning}). Moving the file position
  4271. past the end of the data already written fills the intervening space
  4272. with zeroes. Note that seeking backwards into existing written data
  4273. will change the effective ``end of file'' used by @code{fflush} and
  4274. @code{SEEK_END} (and where the trailing null character is written,
  4275. when closed). Thus, if you wish to do ``random-access'' I/O in a
  4276. memstream, it's important to use @code{fseek} to move the file
  4277. position to the desired data end (using @code{SEEK_POS}) before
  4278. closing it.
  4279. @end deftypefun
  4280. Here is an example of using @code{open_memstream}:
  4281. @smallexample
  4282. @include memstrm.c.texi
  4283. @end smallexample
  4284. This program produces the following output:
  4285. @smallexample
  4286. buf = `hello', size = 5
  4287. buf = `hello, world', size = 12
  4288. @end smallexample
  4289. @node Custom Streams
  4290. @subsection Programming Your Own Custom Streams
  4291. @cindex custom streams
  4292. @cindex programming your own streams
  4293. This section describes how you can make a stream that gets input from an
  4294. arbitrary data source or writes output to an arbitrary data sink
  4295. programmed by you. We call these @dfn{custom streams}. The functions
  4296. and types described here are all GNU extensions.
  4297. @c !!! this does not talk at all about the higher-level hooks
  4298. @menu
  4299. * Streams and Cookies:: The @dfn{cookie} records where to fetch or
  4300. store data that is read or written.
  4301. * Hook Functions:: How you should define the four @dfn{hook
  4302. functions} that a custom stream needs.
  4303. @end menu
  4304. @node Streams and Cookies
  4305. @subsubsection Custom Streams and Cookies
  4306. @cindex cookie, for custom stream
  4307. Inside every custom stream is a special object called the @dfn{cookie}.
  4308. This is an object supplied by you which records where to fetch or store
  4309. the data read or written. It is up to you to define a data type to use
  4310. for the cookie. The stream functions in the library never refer
  4311. directly to its contents, and they don't even know what the type is;
  4312. they record its address with type @code{void *}.
  4313. To implement a custom stream, you must specify @emph{how} to fetch or
  4314. store the data in the specified place. You do this by defining
  4315. @dfn{hook functions} to read, write, change ``file position'', and close
  4316. the stream. All four of these functions will be passed the stream's
  4317. cookie so they can tell where to fetch or store the data. The library
  4318. functions don't know what's inside the cookie, but your functions will
  4319. know.
  4320. When you create a custom stream, you must specify the cookie pointer,
  4321. and also the four hook functions stored in a structure of type
  4322. @code{cookie_io_functions_t}.
  4323. These facilities are declared in @file{stdio.h}.
  4324. @pindex stdio.h
  4325. @deftp {Data Type} {cookie_io_functions_t}
  4326. @standards{GNU, stdio.h}
  4327. This is a structure type that holds the functions that define the
  4328. communications protocol between the stream and its cookie. It has
  4329. the following members:
  4330. @table @code
  4331. @item cookie_read_function_t *read
  4332. This is the function that reads data from the cookie. If the value is a
  4333. null pointer instead of a function, then read operations on this stream
  4334. always return @code{EOF}.
  4335. @item cookie_write_function_t *write
  4336. This is the function that writes data to the cookie. If the value is a
  4337. null pointer instead of a function, then data written to the stream is
  4338. discarded.
  4339. @item cookie_seek_function_t *seek
  4340. This is the function that performs the equivalent of file positioning on
  4341. the cookie. If the value is a null pointer instead of a function, calls
  4342. to @code{fseek} or @code{fseeko} on this stream can only seek to
  4343. locations within the buffer; any attempt to seek outside the buffer will
  4344. return an @code{ESPIPE} error.
  4345. @item cookie_close_function_t *close
  4346. This function performs any appropriate cleanup on the cookie when
  4347. closing the stream. If the value is a null pointer instead of a
  4348. function, nothing special is done to close the cookie when the stream is
  4349. closed.
  4350. @end table
  4351. @end deftp
  4352. @deftypefun {FILE *} fopencookie (void *@var{cookie}, const char *@var{opentype}, cookie_io_functions_t @var{io-functions})
  4353. @standards{GNU, stdio.h}
  4354. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @aculock{}}}
  4355. This function actually creates the stream for communicating with the
  4356. @var{cookie} using the functions in the @var{io-functions} argument.
  4357. The @var{opentype} argument is interpreted as for @code{fopen};
  4358. see @ref{Opening Streams}. (But note that the ``truncate on
  4359. open'' option is ignored.) The new stream is fully buffered.
  4360. The @code{fopencookie} function returns the newly created stream, or a null
  4361. pointer in case of an error.
  4362. @end deftypefun
  4363. @node Hook Functions
  4364. @subsubsection Custom Stream Hook Functions
  4365. @cindex hook functions (of custom streams)
  4366. Here are more details on how you should define the four hook functions
  4367. that a custom stream needs.
  4368. You should define the function to read data from the cookie as:
  4369. @smallexample
  4370. ssize_t @var{reader} (void *@var{cookie}, char *@var{buffer}, size_t @var{size})
  4371. @end smallexample
  4372. This is very similar to the @code{read} function; see @ref{I/O
  4373. Primitives}. Your function should transfer up to @var{size} bytes into
  4374. the @var{buffer}, and return the number of bytes read, or zero to
  4375. indicate end-of-file. You can return a value of @code{-1} to indicate
  4376. an error.
  4377. You should define the function to write data to the cookie as:
  4378. @smallexample
  4379. ssize_t @var{writer} (void *@var{cookie}, const char *@var{buffer}, size_t @var{size})
  4380. @end smallexample
  4381. This is very similar to the @code{write} function; see @ref{I/O
  4382. Primitives}. Your function should transfer up to @var{size} bytes from
  4383. the buffer, and return the number of bytes written. You can return a
  4384. value of @code{0} to indicate an error. You must not return any
  4385. negative value.
  4386. You should define the function to perform seek operations on the cookie
  4387. as:
  4388. @smallexample
  4389. int @var{seeker} (void *@var{cookie}, off64_t *@var{position}, int @var{whence})
  4390. @end smallexample
  4391. For this function, the @var{position} and @var{whence} arguments are
  4392. interpreted as for @code{fgetpos}; see @ref{Portable Positioning}.
  4393. After doing the seek operation, your function should store the resulting
  4394. file position relative to the beginning of the file in @var{position}.
  4395. Your function should return a value of @code{0} on success and @code{-1}
  4396. to indicate an error.
  4397. You should define the function to do cleanup operations on the cookie
  4398. appropriate for closing the stream as:
  4399. @smallexample
  4400. int @var{cleaner} (void *@var{cookie})
  4401. @end smallexample
  4402. Your function should return @code{-1} to indicate an error, and @code{0}
  4403. otherwise.
  4404. @deftp {Data Type} cookie_read_function_t
  4405. @standards{GNU, stdio.h}
  4406. This is the data type that the read function for a custom stream should have.
  4407. If you declare the function as shown above, this is the type it will have.
  4408. @end deftp
  4409. @deftp {Data Type} cookie_write_function_t
  4410. @standards{GNU, stdio.h}
  4411. The data type of the write function for a custom stream.
  4412. @end deftp
  4413. @deftp {Data Type} cookie_seek_function_t
  4414. @standards{GNU, stdio.h}
  4415. The data type of the seek function for a custom stream.
  4416. @end deftp
  4417. @deftp {Data Type} cookie_close_function_t
  4418. @standards{GNU, stdio.h}
  4419. The data type of the close function for a custom stream.
  4420. @end deftp
  4421. @ignore
  4422. Roland says:
  4423. @quotation
  4424. There is another set of functions one can give a stream, the
  4425. input-room and output-room functions. These functions must
  4426. understand stdio internals. To describe how to use these
  4427. functions, you also need to document lots of how stdio works
  4428. internally (which isn't relevant for other uses of stdio).
  4429. Perhaps I can write an interface spec from which you can write
  4430. good documentation. But it's pretty complex and deals with lots
  4431. of nitty-gritty details. I think it might be better to let this
  4432. wait until the rest of the manual is more done and polished.
  4433. @end quotation
  4434. @end ignore
  4435. @c ??? This section could use an example.
  4436. @node Formatted Messages
  4437. @section Formatted Messages
  4438. @cindex formatted messages
  4439. On systems which are based on System V messages of programs (especially
  4440. the system tools) are printed in a strict form using the @code{fmtmsg}
  4441. function. The uniformity sometimes helps the user to interpret messages
  4442. and the strictness tests of the @code{fmtmsg} function ensure that the
  4443. programmer follows some minimal requirements.
  4444. @menu
  4445. * Printing Formatted Messages:: The @code{fmtmsg} function.
  4446. * Adding Severity Classes:: Add more severity classes.
  4447. * Example:: How to use @code{fmtmsg} and @code{addseverity}.
  4448. @end menu
  4449. @node Printing Formatted Messages
  4450. @subsection Printing Formatted Messages
  4451. Messages can be printed to standard error and/or to the console. To
  4452. select the destination the programmer can use the following two values,
  4453. bitwise OR combined if wanted, for the @var{classification} parameter of
  4454. @code{fmtmsg}:
  4455. @vtable @code
  4456. @item MM_PRINT
  4457. Display the message in standard error.
  4458. @item MM_CONSOLE
  4459. Display the message on the system console.
  4460. @end vtable
  4461. The erroneous piece of the system can be signalled by exactly one of the
  4462. following values which also is bitwise ORed with the
  4463. @var{classification} parameter to @code{fmtmsg}:
  4464. @vtable @code
  4465. @item MM_HARD
  4466. The source of the condition is some hardware.
  4467. @item MM_SOFT
  4468. The source of the condition is some software.
  4469. @item MM_FIRM
  4470. The source of the condition is some firmware.
  4471. @end vtable
  4472. A third component of the @var{classification} parameter to @code{fmtmsg}
  4473. can describe the part of the system which detects the problem. This is
  4474. done by using exactly one of the following values:
  4475. @vtable @code
  4476. @item MM_APPL
  4477. The erroneous condition is detected by the application.
  4478. @item MM_UTIL
  4479. The erroneous condition is detected by a utility.
  4480. @item MM_OPSYS
  4481. The erroneous condition is detected by the operating system.
  4482. @end vtable
  4483. A last component of @var{classification} can signal the results of this
  4484. message. Exactly one of the following values can be used:
  4485. @vtable @code
  4486. @item MM_RECOVER
  4487. It is a recoverable error.
  4488. @item MM_NRECOV
  4489. It is a non-recoverable error.
  4490. @end vtable
  4491. @deftypefun int fmtmsg (long int @var{classification}, const char *@var{label}, int @var{severity}, const char *@var{text}, const char *@var{action}, const char *@var{tag})
  4492. @standards{XPG, fmtmsg.h}
  4493. @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acsafe{}}
  4494. Display a message described by its parameters on the device(s) specified
  4495. in the @var{classification} parameter. The @var{label} parameter
  4496. identifies the source of the message. The string should consist of two
  4497. colon separated parts where the first part has not more than 10 and the
  4498. second part not more than 14 characters. The @var{text} parameter
  4499. describes the condition of the error, the @var{action} parameter possible
  4500. steps to recover from the error and the @var{tag} parameter is a
  4501. reference to the online documentation where more information can be
  4502. found. It should contain the @var{label} value and a unique
  4503. identification number.
  4504. Each of the parameters can be a special value which means this value
  4505. is to be omitted. The symbolic names for these values are:
  4506. @vtable @code
  4507. @item MM_NULLLBL
  4508. Ignore @var{label} parameter.
  4509. @item MM_NULLSEV
  4510. Ignore @var{severity} parameter.
  4511. @item MM_NULLMC
  4512. Ignore @var{classification} parameter. This implies that nothing is
  4513. actually printed.
  4514. @item MM_NULLTXT
  4515. Ignore @var{text} parameter.
  4516. @item MM_NULLACT
  4517. Ignore @var{action} parameter.
  4518. @item MM_NULLTAG
  4519. Ignore @var{tag} parameter.
  4520. @end vtable
  4521. There is another way certain fields can be omitted from the output to
  4522. standard error. This is described below in the description of
  4523. environment variables influencing the behavior.
  4524. The @var{severity} parameter can have one of the values in the following
  4525. table:
  4526. @cindex severity class
  4527. @vtable @code
  4528. @item MM_NOSEV
  4529. Nothing is printed, this value is the same as @code{MM_NULLSEV}.
  4530. @item MM_HALT
  4531. This value is printed as @code{HALT}.
  4532. @item MM_ERROR
  4533. This value is printed as @code{ERROR}.
  4534. @item MM_WARNING
  4535. This value is printed as @code{WARNING}.
  4536. @item MM_INFO
  4537. This value is printed as @code{INFO}.
  4538. @end vtable
  4539. The numeric value of these five macros are between @code{0} and
  4540. @code{4}. Using the environment variable @code{SEV_LEVEL} or using the
  4541. @code{addseverity} function one can add more severity levels with their
  4542. corresponding string to print. This is described below
  4543. (@pxref{Adding Severity Classes}).
  4544. @noindent
  4545. If no parameter is ignored the output looks like this:
  4546. @smallexample
  4547. @var{label}: @var{severity-string}: @var{text}
  4548. TO FIX: @var{action} @var{tag}
  4549. @end smallexample
  4550. The colons, new line characters and the @code{TO FIX} string are
  4551. inserted if necessary, i.e., if the corresponding parameter is not
  4552. ignored.
  4553. This function is specified in the X/Open Portability Guide. It is also
  4554. available on all systems derived from System V.
  4555. The function returns the value @code{MM_OK} if no error occurred. If
  4556. only the printing to standard error failed, it returns @code{MM_NOMSG}.
  4557. If printing to the console fails, it returns @code{MM_NOCON}. If
  4558. nothing is printed @code{MM_NOTOK} is returned. Among situations where
  4559. all outputs fail this last value is also returned if a parameter value
  4560. is incorrect.
  4561. @end deftypefun
  4562. There are two environment variables which influence the behavior of
  4563. @code{fmtmsg}. The first is @code{MSGVERB}. It is used to control the
  4564. output actually happening on standard error (@emph{not} the console
  4565. output). Each of the five fields can explicitly be enabled. To do
  4566. this the user has to put the @code{MSGVERB} variable with a format like
  4567. the following in the environment before calling the @code{fmtmsg} function
  4568. the first time:
  4569. @smallexample
  4570. MSGVERB=@var{keyword}[:@var{keyword}[:@dots{}]]
  4571. @end smallexample
  4572. Valid @var{keyword}s are @code{label}, @code{severity}, @code{text},
  4573. @code{action}, and @code{tag}. If the environment variable is not given
  4574. or is the empty string, a not supported keyword is given or the value is
  4575. somehow else invalid, no part of the message is masked out.
  4576. The second environment variable which influences the behavior of
  4577. @code{fmtmsg} is @code{SEV_LEVEL}. This variable and the change in the
  4578. behavior of @code{fmtmsg} is not specified in the X/Open Portability
  4579. Guide. It is available in System V systems, though. It can be used to
  4580. introduce new severity levels. By default, only the five severity levels
  4581. described above are available. Any other numeric value would make
  4582. @code{fmtmsg} print nothing.
  4583. If the user puts @code{SEV_LEVEL} with a format like
  4584. @smallexample
  4585. SEV_LEVEL=[@var{description}[:@var{description}[:@dots{}]]]
  4586. @end smallexample
  4587. @noindent
  4588. in the environment of the process before the first call to
  4589. @code{fmtmsg}, where @var{description} has a value of the form
  4590. @smallexample
  4591. @var{severity-keyword},@var{level},@var{printstring}
  4592. @end smallexample
  4593. The @var{severity-keyword} part is not used by @code{fmtmsg} but it has
  4594. to be present. The @var{level} part is a string representation of a
  4595. number. The numeric value must be a number greater than 4. This value
  4596. must be used in the @var{severity} parameter of @code{fmtmsg} to select
  4597. this class. It is not possible to overwrite any of the predefined
  4598. classes. The @var{printstring} is the string printed when a message of
  4599. this class is processed by @code{fmtmsg} (see above, @code{fmtsmg} does
  4600. not print the numeric value but instead the string representation).
  4601. @node Adding Severity Classes
  4602. @subsection Adding Severity Classes
  4603. @cindex severity class
  4604. There is another possibility to introduce severity classes besides using
  4605. the environment variable @code{SEV_LEVEL}. This simplifies the task of
  4606. introducing new classes in a running program. One could use the
  4607. @code{setenv} or @code{putenv} function to set the environment variable,
  4608. but this is toilsome.
  4609. @deftypefun int addseverity (int @var{severity}, const char *@var{string})
  4610. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{}}}
  4611. This function allows the introduction of new severity classes which can be
  4612. addressed by the @var{severity} parameter of the @code{fmtmsg} function.
  4613. The @var{severity} parameter of @code{addseverity} must match the value
  4614. for the parameter with the same name of @code{fmtmsg}, and @var{string}
  4615. is the string printed in the actual messages instead of the numeric
  4616. value.
  4617. If @var{string} is @code{NULL} the severity class with the numeric value
  4618. according to @var{severity} is removed.
  4619. It is not possible to overwrite or remove one of the default severity
  4620. classes. All calls to @code{addseverity} with @var{severity} set to one
  4621. of the values for the default classes will fail.
  4622. The return value is @code{MM_OK} if the task was successfully performed.
  4623. If the return value is @code{MM_NOTOK} something went wrong. This could
  4624. mean that no more memory is available or a class is not available when
  4625. it has to be removed.
  4626. This function is not specified in the X/Open Portability Guide although
  4627. the @code{fmtsmg} function is. It is available on System V systems.
  4628. @end deftypefun
  4629. @node Example
  4630. @subsection How to use @code{fmtmsg} and @code{addseverity}
  4631. Here is a simple example program to illustrate the use of both
  4632. functions described in this section.
  4633. @smallexample
  4634. @include fmtmsgexpl.c.texi
  4635. @end smallexample
  4636. The second call to @code{fmtmsg} illustrates a use of this function as
  4637. it usually occurs on System V systems, which heavily use this function.
  4638. It seems worthwhile to give a short explanation here of how this system
  4639. works on System V. The value of the
  4640. @var{label} field (@code{UX:cat}) says that the error occurred in the
  4641. Unix program @code{cat}. The explanation of the error follows and the
  4642. value for the @var{action} parameter is @code{"refer to manual"}. One
  4643. could be more specific here, if necessary. The @var{tag} field contains,
  4644. as proposed above, the value of the string given for the @var{label}
  4645. parameter, and additionally a unique ID (@code{001} in this case). For
  4646. a GNU environment this string could contain a reference to the
  4647. corresponding node in the Info page for the program.
  4648. @noindent
  4649. Running this program without specifying the @code{MSGVERB} and
  4650. @code{SEV_LEVEL} function produces the following output:
  4651. @smallexample
  4652. UX:cat: NOTE2: invalid syntax
  4653. TO FIX: refer to manual UX:cat:001
  4654. @end smallexample
  4655. We see the different fields of the message and how the extra glue (the
  4656. colons and the @code{TO FIX} string) is printed. But only one of the
  4657. three calls to @code{fmtmsg} produced output. The first call does not
  4658. print anything because the @var{label} parameter is not in the correct
  4659. form. The string must contain two fields, separated by a colon
  4660. (@pxref{Printing Formatted Messages}). The third @code{fmtmsg} call
  4661. produced no output since the class with the numeric value @code{6} is
  4662. not defined. Although a class with numeric value @code{5} is also not
  4663. defined by default, the call to @code{addseverity} introduces it and
  4664. the second call to @code{fmtmsg} produces the above output.
  4665. When we change the environment of the program to contain
  4666. @code{SEV_LEVEL=XXX,6,NOTE} when running it we get a different result:
  4667. @smallexample
  4668. UX:cat: NOTE2: invalid syntax
  4669. TO FIX: refer to manual UX:cat:001
  4670. label:foo: NOTE: text
  4671. TO FIX: action tag
  4672. @end smallexample
  4673. Now the third call to @code{fmtmsg} produced some output and we see how
  4674. the string @code{NOTE} from the environment variable appears in the
  4675. message.
  4676. Now we can reduce the output by specifying which fields we are
  4677. interested in. If we additionally set the environment variable
  4678. @code{MSGVERB} to the value @code{severity:label:action} we get the
  4679. following output:
  4680. @smallexample
  4681. UX:cat: NOTE2
  4682. TO FIX: refer to manual
  4683. label:foo: NOTE
  4684. TO FIX: action
  4685. @end smallexample
  4686. @noindent
  4687. I.e., the output produced by the @var{text} and the @var{tag} parameters
  4688. to @code{fmtmsg} vanished. Please also note that now there is no colon
  4689. after the @code{NOTE} and @code{NOTE2} strings in the output. This is
  4690. not necessary since there is no more output on this line because the text
  4691. is missing.