Home > Software design >  Getting data from a .txt file in C
Getting data from a .txt file in C

Time:04-07

I'm new to C and I have to read data from a file, and I need to store that data in an array. I'm using FILE *fptr; fptr = fopen(¨filename.txt¨, ¨r¨) to read and fscanf(fptr,"%d", &num); to get the file data, however when compiling I only seem to get the memory location for it (I think? the file I'm using to try the code out has the number 5368 and I'm getting 6422296)

int main(void)

    {
    FILE *fptr;
    fptr = fopen("example.txt" , "r");
    if ((fptr = fopen("example.txt","r")) == NULL)
    {
      printf("Error! opening file");
      exit(1);
    }
    int num;
    fscanf(fptr,"%d", &num);
    printf("VALUE OF NUM IS %d", &num);

    fclose(fptr);
    return 0;
    }

CodePudding user response:

Here a minimal example demonstrating reading a couple of numbers from filename.txt into an array num. You need to add error handling, and if you cannot fix the size (LEN) then either calculate it by figuring out how numbers is in the file, or realloc the size of the num array as needed:

#include <stdio.h>

#define LEN 2

int main() {
    FILE *fptr = fopen("./filename.txt", "r");
    int num[LEN];
    for(int i = 0; i < LEN; i  ) {
        fscanf(fptr, "%d", num   i);
        printf("%d\n", num[i]);
    }
    fclose(fptr);
}
  • Related