Using Malloc to Read a File Dynamically

  • #1
38
2
Homework Statement:
Read a file dynamically
Relevant Equations:
-
C:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<time.h>
int main(){
        
    int index=1;
    int *arr;
    int data;
    char *c;
    FILE *fp;
    int input,inp;
    arr=(int*)malloc(sizeof(int));
    fp=fopen("list2.txt","r");
    input=fscanf(fp,"%d",&inp);
    while(input!=EOF){
        printf("%d",inp);
        if(inp!=','){
            arr[index-1]=inp;
            index++;
            arr=realloc(arr,(index)*sizeof(int));
        }
        input=fscanf(fp,"%d",&inp);
    }
    fclose(fp);
    free(arr);
    return 0;
}


I want to read a file that file contains-> 1,2,3,5,7,888, But my code goes into loop, why? How can I fixed this?
 

Answers and Replies

  • #2
12,837
6,720
I would put print statement in to see what value of input is being returned and what the value of EOF is.

The while loop will only terminate when input==EOF

Also I would look at the inp value to see if it matches the number your expect. Will inp==',' when you run the program or will you have to read the ',' to get to the next number?

Here's an example that reads multiple data types:

https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/rtref/fscanf.htm
 
  • #3
35,057
6,793
@anonim, your code is supposed to go into a loop. Do you mean an infinite loop? What output do you get before your code goes into an infinite loop, assuming that's what you meant?
 

Related Threads on Using Malloc to Read a File Dynamically

Replies
12
Views
24K
  • Last Post
Replies
14
Views
1K
  • Last Post
Replies
5
Views
6K
Replies
3
Views
921
Replies
0
Views
1K
  • Last Post
Replies
2
Views
2K
Replies
2
Views
2K
Replies
3
Views
722
  • Last Post
Replies
2
Views
1K
Top