granddave

Number in file to array

Nov 18th, 2015
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void readFile(int*, int*);
  5. #define FILE_NAME "numbers.txt"
  6.  
  7. void main(void)
  8. {
  9.     int *array; //main-array with numbers
  10.     int rows;   //number of elements in array
  11.  
  12.     readFile(&array, &rows);
  13.     system("pause");
  14. }
  15.  
  16. void readFile(int *arr, int *pRows)
  17. {
  18.     int rowCount;  // number of rows i file (except the first row) 
  19.     int num = 0;   // temporary storage
  20.     int i;
  21.     FILE *infile;
  22.  
  23.     infile = fopen(FILE_NAME, "r");
  24.     if (infile == NULL)
  25.     {
  26.         printf("couldn't open file");
  27.         exit(1);
  28.     }
  29.  
  30.     fscanf(infile, "%d", &rowCount); //reads first row in file
  31.     int *integers = malloc(sizeof(int)* rowCount);
  32.  
  33.     for (i = 0; i < rowCount; i++)
  34.     {
  35.         fscanf(infile, "%d", &num);
  36.         integers[i] = num;
  37.     }
  38.  
  39.     for (i = 0; i < rowCount; i++) //copies numbers from internal array to main array
  40.     {
  41.         *(arr + i) = integers[i];
  42.     }
  43.  
  44.     *pRows = rowCount;
  45.  
  46.     fclose(infile);
  47.     free(integers);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment