O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code Sample 11.2: Reading Multiple Integers from a File

Although this code might compile, it will not do exactly what you expect. Part of the problem is that, as you saw with fprintf, the function works on fields and not on chains of numbers. Therefore, you need to loop through the array and read in each item by passing by reference:

int nItem, sInt[10];
for ( nItem = 0; nItem < 10; nItem++ )
{
      fscanf ( hFile, " %d ", &sInt[nItem] );
}

When used together, the two functions fprintf and fscanf can provide some powerful formatted data file-manipulation possibilities. If, for example, you need to create an address book application, you can write out, in a formatted fashion, the address details and read them back in relatively easily.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required