Ad

How Do I Save Process Values Saved In A .txt File To 4 Different Arrays In C

Given processes.txt with the following information

0 4 96 30
3 2 32 40
5 1 100 20
20 3 4 30

How do I save each row of the file as elements of 4 different arrays in c? i.e.

int arr1 = [0,4,96,30]
int arr2 = [3,2,32,40]
int arr3 = [5,1,100,20]
int arr[4] = [20,3,4,30]

Here is my code where I have loaded the .txt file but do not know how to store the values in an integer array. My code produces garbage values.

How can I write the program?

    #include <stdio.h>

    int main(int argc, char *argv[])
    {
     FILE *fp;
     char *filename;
     char ch;

      // Check if a filename has been specified in the command
      if (argc < 2)
       {
            printf("Missing Filename\n");
            return(1);
       }
       else
      {
            filename = argv[1];
            printf("Filename : %s\n", filename);
       }

       // Open file in read-only mode
       fp = fopen(filename,"r");

       // If file opened successfully, then print the contents
       if ( fp )
          {
            printf("File contents:\n");
            while ( (ch = fgetc(fp)) != EOF )
               {
                    printf("%c",ch);
               }

           }
       else
          {
             printf("Failed to open the file\n");
            }
       // Saving the contents of the file in a Number Array
            int numberArray[16];
            int i;

        for (i = 0; i < 16; i++)
        {
            fscanf(fp, "%d", &numberArray[i]);
        }

        for (i = 0; i < 16; i++)
        {
            printf("Number is: %d\n\n", numberArray[i]);
        }


    return(0);
    }
Ad

Answer

You have to reset the pointer fp to start of file. Because the while loop: while ( (ch = fgetc(fp)) != EOF ), the pointer fp is at the end of file.

int numberArray[16];
int i;
fseek(fp, 0, SEEK_SET);

The for loop for fscanf should be replaced by while loop:

        int numberArray[16];
        int i = 0;
        fseek(fp, 0, SEEK_SET);
        while(fscanf(fp, "%d", &numberArray[i]) == 1 && i < 16)
        {
            i++;
        }
        // Then when you print the value from 0 to i
        for (int j = 0; j < i; j++)
        {
            printf("Number is: %d\n\n", numberArray[j]);
        }

Do not forget to close the file when you do not need to use it:

fclose(fp);

Now, if you want to separate the numberArray to 4 array arr1, arr2, arr3 and arr4. You can assign first 4 elements of numberArray (form 0 to 3) to arr1, then the next 4 elements (from 4 to 7) to arr2 and so on.

Ad
source: stackoverflow.com
Ad