In: Computer Science
FILE *fin = NULL;
fin = fopen(in.txt, "r");
int *arr = (int *) malloc (sizeof (int) * fin);
*****************************************************
If I want to open a in.txt, only the integer in the file, is the malloc code correct?
What if the in.txt includes the string and integer, how can I use the malloc?
Thanks
`Hey,
Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
The code above is indeed not correct. There is 1 major flaw that the fin can't be used to pass it as size of array. We don't know the file pointer size and we are converting it to the size of array.
For example file with only 2 integers as
1 2
It will return size a much larger and we will be wasting the memory.
We can do 1 thing which is we have to first count the number of integers in the file and then we will use it as
int *arr = (int *) malloc (sizeof (int) * ct); where ct is the count of integers
Below is the full code in C
FILE *fin = NULL;
fin = fopen(in.txt, "r");
int ct = 0; fscanf (file, "%d", &i); while (!feof (file)) { ct++; //printf ("%d ", i); fscanf (file, "%d", &i); } fclose (file);
int *arr = (int *) malloc (sizeof (int) * ct);
Kindly revert for any queries
Thanks.