Comp Sci Using Malloc to Read a File Dynamically

  • Thread starter Thread starter anonim
  • Start date Start date
  • Tags Tags
    File
Click For Summary
The discussion focuses on a C program that uses `malloc` to read integers from a file but encounters an infinite loop issue. The primary problem arises from the way the program handles input, particularly the presence of commas in the data file. Participants suggest checking the value of `inp` to ensure it does not equal a comma when reading integers, as this could cause the loop to continue indefinitely. Additionally, using print statements to debug the values of `input` and `inp` is recommended to identify where the logic fails. The conversation emphasizes the importance of correctly parsing the input data to avoid infinite loops.
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?
 
Physics news 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
1K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
11K
  • · Replies 1 ·
Replies
1
Views
3K