Brandon Tomblinson
Brandon Tomblinson

Reputation: 316

fscanf only scans in the first value of my file

#include <stdio.h>
#include <stdlib.h>

struct account{
int accountId;
char *name;
double amount;
};
int main(int argc, char **argv)
{
FILE *file=fopen(argv[1],"r");
struct account *Ptr;
int i,j;
int size=0;

fscanf(file,"%d",&size);
if(size==0)
{
    printf("Unable to open file");
    return 0;
}
printf("%d",size);
Ptr=malloc(sizeof(struct account)*size);

for(i=0;i<size;i++)
{
    fscanf(file,"%d%s%lf\n",&(Ptr+i)->accountId,(Ptr+i)->name,&(Ptr+i)->amount);
}

for(j=0;j<size;j++)
{
    printf("%d%s%lf\n",((Ptr+j)->accountId),(Ptr+j)->name,((Ptr+j)->amount));
}

fclose(file);
free(Ptr);

return 0;

}

This is used to read in the input file 2 2 Harry 23.45 8 Sally 100.91

Somehow the code reads in the first 2 for size and the second 2 during the for loop but nothing else

Upvotes: 1

Views: 413

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Your code has undefined behavior, because you are reading data into an uninitialized pointer:

fscanf(file,"%d%s%lf\n",&(Ptr+i)->accountId,(Ptr+i)->name,&(Ptr+i)->amount);
//                                                   ^^^^
// This pointer is uninitialized ----------------------+

There are three ways to address this:

  • Make name an array, rather than a pointer, e.g. char name[MAX_NAME], or
  • Use malloc to allocate space to name before reading data into it.
  • Read into a temporary buffer, then malloc the exact number of chars.

Upvotes: 1

Related Questions