By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,948 Members | 1,215 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,948 IT Pros & Developers. It's quick & easy.

Reading Data From File

P: 16
Ok, I'm trying to read in some integers from a file for some reason however my array is not filling up. I know it's not filling up because I can watch the array in the debugger. My code looks correct but it's not working. The the "fileName" array works properly but the "data" array is not.

Expand|Select|Wrap|Line Numbers
  1.   scanf("%s",fileName);
  2.     printf("%s\n",fileName);
  3.     sp = fopen(fileName,"r");
  4.     for(i= 0; i<10; i++){
  5.     while(k=(fscanf(sp,"%i",&data[i]) == 1)){
  6.         printf("%10i\n",*data);
  7.         b += k++ ;// b is number of  values read into data[]

Doesn't the fscanf function run until there is no more data to be read ? If this is true why do I need the for loop to move through the array

Since an arrays name is a pointer to the first element in the array, why do I need the ampersand in the while loop?
Nov 12 '08 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 1,764
Read this .
Nov 12 '08 #2

Expert 10K+
P: 11,448
If your file contains the correct numbers the while loop reads them all and stores
them all in the i ==0 array element. You shouldn't put a while loop inside a for
loop. The overall structure should be something like this:

Expand|Select|Wrap|Line Numbers
  1. for (i= 0; i < array_length; i++)
  2.    if (fscanf(sp, "%i", data+i) != 1)
  3.       /* something's rotten in the state of Denmark */
  4.    else
  5.       /* just read and stored data[i] */
kind regards,

Nov 12 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.