Josh McCloud
Josh McCloud

Reputation: 39

Is there a method to scanf elements from a file into an array using a while loop?

I am attempting to have void getMessage() read message from msgfile.txt, one element at a time. The msgfile.txt has 26 integer digits. I am using a while loop to get every integer (26 total) be read in a similar way as the 'void getCode()', except utilizing a while loop and not a for loops, but the way I have it is a while loop followed a for loop. This isn't executing correctly.

Here is the input found in the msgfile.txt, except its not in a row, but rather column:

19546 14501 17309 13027 16149 21512 18035 14014 15700 12515 16514 18207 13407 14837 16842 21037 15333 13244 21224 16321 14146 16014 20727 12804 18811 13711

Expected output is an array 'numbers[26]' containing the elements of the msgfile.txt:

numbers[0] : 19546 numbers[1] : 14501 etc.

#include <stdio.h>
# define LISTNUM 26

void getCode();
void getMessage(int n, int numbers[LISTNUM]);
//void sortMessage();
//void decodeMessage();

int main( void ) {
    
    
    int n,i;
    int numbers[LISTNUM];
    
    
    FILE *fp;
    fp = fopen( "msgfile.txt", "r" );
    if( fp == NULL )
    {
        printf( "could not open msgfile.txt\n" );
        return 1;
    }

    while( !feof( fp ) )
    {
        fscanf( fp, "%d\n", &n );
        printf( "%d\n", n );
    }
    
    
        getCode();
        getMessage(n,numbers);
        //sortMessage();
        //decodeMessage();
}
        
    
    
    
    
void getMessage(int n, int numbers[LISTNUM])
{
    
    fopen_s(fopen, "msgfile.txt","r");
    
    while(!feof(fopen))
    {
        for(int i = 0; i < LISTNUM; i++)
        {
            scanf(fopen,"%d", &numbers[LISTNUM]);
        }
    }
}

void getCode()
    {
        FILE *filepointer2;
        
        char character[52];
        
        /*step 2: open codefile.txt and read from it*/
        
        filepointer2 = fopen("codefile.txt", "r");
        
        if (filepointer2 == NULL)/*if file does not open*/
        
        {
        
        printf("Can't open file for reading.\n");
        
        }
        
        else
        
        {
        
        /*if file opens read the characters into the array*/
        
        for(int i=0;i<52;i++){
        
        fscanf(filepointer2, "%c", &character[i]);
        
        }
    }

Upvotes: 0

Views: 34

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

&numbers[LISTNUM] in scanf(fopen,"%d", &numbers[LISTNUM]) looks suspicious. Replace it with &numbers[i]

Upvotes: 1

Related Questions