Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Ian Collins Newsgroups: comp.lang.c++ Subject: Re: What's the most secure way to read a long int ? Date: Sat, 13 Aug 2011 21:20:07 +1200 Lines: 36 Message-ID: <9amtu7FdetU2@mid.individual.net> References: <4e463fcc$0$32662$426a74cc@news.free.fr> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net sGTPtroBh6vTb9jsiEz2Cgldi4YR9NWikVi1o548gJJn68m0Dy Cancel-Lock: sha1:MKj6AK4+SyV1MRd938nQ0CrC9Ls= User-Agent: Mozilla/5.0 (X11; U; SunOS i86pc; en-US; rv:1.9.2.9) Gecko/20101021 Lightning/1.0b2 Thunderbird/3.1.4 In-Reply-To: <4e463fcc$0$32662$426a74cc@news.free.fr> Xref: x330-a1.tempe.blueboxinc.net comp.lang.c++:8771 On 08/13/11 09:12 PM, Julien wrote: > Hello, > > I used cppcheck to detect problems and had this : > (warning) scanf without field width limits can crash with huge input data > > void read_cputime(double& cpu) { > long int c; > cpu = 0; > FILE* f = fopen(CPU_TIME, "r"); > if (!f) return; > int n = fscanf(f, "%ld",&c);<-- pb detected > fclose(f); > if (n != 1) return; > cpu = c; > } > > First I thought about adding a number in the format : > int n = fscanf(f, "%4ld",&c); > > But I want the code to be portable (it must ok for 32 bits or 64 bits). > So what to use ? A macro ? A c++ const ? C++ internal library (cin ?) ? > other ? Do it the C++ way: std::ifstream f( CPU_TIME ); if (!f) return; long c; f >> c; if(!f) return; -- Ian Collins