0

I am learning C and practicing by writing a small program that reads integers from a textfile and stores them into an array. However, the integers never get stored somehow and the array is empty.

 int readNumbers(int array[], char* fname) {                                                                                                                                                                                               
 78                                                                                                                                                                      
 79                                                                                                                                                                                             
 80     int numberRead = 0;                                                                                                                                                                                                                   
 81     FILE* fp;                                                                                                                                                                                                                             
 82     int ch;                                                                                                                                                                                                                               
 83     int i = 0;                                                                                                                                                                                                                            
 84                                                                                                                                                                                                                                           
 85                                                                                                                                                                                          
 86                                                                                                                                                                                                                                  
 87     fp = fopen(fname, "r");                                                                                                                                                                                                               
 88     // Test to see if the file was opened correctly                                                                                                                                                                                       
 89                                                                                                                                                                                                                                   
 90     if (fp == NULL) {                                                                                                                                                                                                                     
 91             printf("Error opening file\n");                                                                                                                                                                                               
 92             return;                                                                                                                                                                                                                       
 93     }                                                                                                                                                                                                                                     
 94     // Now read until end of file                                                                                                                                                                                                         
 95                                                                                                                                                                                                                                  
 96     while (ch = fgetc(fp) != EOF && isdigit(ch)) {                                                                                                                                                                                        
 97             array[i++] = ch;                                                                                                                                                                                                              
 98     }                                                                                                                                                                                                                                     
 99     if (ferror(fp)) {                                                                                                                                                                                                                     
100             return;                                                                                                                                                                                                                       
101     }                                                                                                                                                                                                                                     
102     // Close the file pointer                                                                                                                                                                                                             
103                                                                                                                                                                                                                                 
104     fclose(fp);                                                                                                                                                                                                                           
105                                                                                                                                                                                                                                           
106     // Return the number of items read                                                                                                                                                                                                    
107     return numberRead;                                                                                                                                                                          
108 }

The text file would be something like this:

1 2 3 4 5 6 7 8 9

Thanks in advance.

I've updated the code. This almost works, but it interprets characters such as 55 as 5 and 5. So my array would have two 5's.

 while ((ch =fgetc(fp)) != EOF) {                                                                                                                                                                                                      
 97             if (ch != ' ' && ch != '\n') {                                                                                                                                                                                                
 98                     array[counter] = ch - '0';                                                                                                                                                                                            
 99                     counter++;                                                                                                                                                                                                            
100                     numberRead++;                                                                                                                                                                                                         
101             }                                                                                                                                                                                                                             
102     }
jww
  • 97,681
  • 90
  • 411
  • 885
mrQWERTY
  • 4,039
  • 13
  • 43
  • 91
  • 2
    change `ch = fgetc(fp) != EOF` to `(ch = fgetc(fp)) != EOF` . The comparison operator has higher precedence than the assignment. – M.M Oct 07 '14 at 01:34
  • Your function returns without closing the file in case of `ferror` which is a bit strange. Also it is illegal to have `return;` without an argument. – M.M Oct 07 '14 at 01:35
  • Note: Interesting that code is using `if (ferror(fp))`. If true, `fp` is not closed. – chux - Reinstate Monica Oct 07 '14 at 02:19
  • I got this working. However, fgetc would interpret a number such as 55 into 5 and 5. I'll post the updated code for clarification. – mrQWERTY Oct 07 '14 at 02:40

3 Answers3

1

you should us the parentheses here while (ch = fgetc(fp) != EOF && isdigit(ch)) , it should be while ((ch = fgetc(fp)) != EOF && isdigit(ch)) otherwise you will store in ch the value of fgetc(fp) != EOF which is eather 1 or 0 ( TRUE or FALSE)

Farouq Jouti
  • 1,657
  • 9
  • 15
1

To expand on what Matt McNabb said in the comment, you can't have return without a value (unless it's inside a void function). Your readNumbers() function is declared to return int so all return paths must return an int. You may like to return -1 if there's a file error, since 0 is (kind of :) ) a valid number of chars to read.

Since there are spaces between the digits in your input file you will need to change the logic in your while loop.

while ((ch = fgetc(fp)) != EOF && isdigit(ch))

will fail as soon as it reads a non-digit char.

I should also mention that you are storing the numerical value of each char you read into your array, which might not be what you want. Eg, in ASCII a '0' char will have a numeric value of 48, '1' has a value of 49, etc.

PS. Make sure that the function that calls readNumbers() provides an array big enough to handle any possible result...


Try to avoid using exit() deep within your program, when practical, and just use it in main(). Also, rather than just killing your program stone dead with exit() it's much better to print some kind of error message first (usually to stderr), and then die gracefully. As for creating suitable error messages, check out the <stdio.h> function perror(), and take a look at <errno.h>.

You can either print the error message in readNumbers() and return -1, and then let the calling function (eg main()) decide if the error's so bad that the program should die. Or let the calling function handle the printing of the error message, too.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
1
// this following code modification will handle your most recent question

int value = 0; // place to accumulate numbers
int inNumber = 0; // to avoid spurious input in array[]

// note: the following expects that 'ch' is defined as an integer
while ((ch =fgetc(fp)) != EOF)
{
    if (ch >= '0' && ch <= '9') // only process numeric characters
    {
        value *= 10;
        value += (ch - 0x30); // convert alpha to binary 
        inNumber = 1;
    }
    else
    { // break between numbers
        if( 1 == inNumber )
        {
            array[counter] = value;
            counter++;
            numberRead++;
            value = 0; // reset for next number
            inNumber = 0;
        }
    }
}
user3629249
  • 16,402
  • 1
  • 16
  • 17