Using Malloc to Read a File Dynamically

  • Context: Comp Sci 
  • Thread starter Thread starter anonim
  • Start date Start date
  • Tags Tags
    File
anonim
Messages
39
Reaction score
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?
 
on Phys.org
I would put print statement into 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
 
@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?
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 1 ·
Replies
1
Views
11K
  • · Replies 1 ·
Replies
1
Views
3K